开发者

Why does the istitle() string method return false if the string is clearly in title-case?

Of the istitle() string method, the Python 2.6.5 manual reads:

Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return fals开发者_Go百科e otherwise.

But in this case it returns false:

>>> book = 'what every programmer must know'
>>> book.title()
'What Every Programmer Must Know'
>>> book.istitle()
False

What am I missing?


book.title() does not change the variable book. It just returns the string in title case.

>>> book.title()
'What Every Programmer Must Know'
>>> book             # still not in title case
'what every programmer must know'
>>> book.istitle()   # hence it returns False.
False
>>> book.title().istitle()   # returns True as expected
True


The method title() doesn't mutate the string (strings are immutable in Python). It creates a new string which you must assign to your variable:

>>> book = 'what every programmer must know'
>>> book = book.title()
>>> book.istitle()
True


Probably because you are still calling istitle() on the original book.

Try book.title().istitle() instead....


Do the following:

print book

after you do book.title(). You will see that book hasn't changed.

The reason is that book.title() creates a new string. The name book still refers to the original string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜