views:

79

answers:

4

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 false 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?

+3  A: 

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

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

mikera
+8  A: 

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
KennyTM
OK, that is what I was missing! Thanks. The documentation actually does say that .title() returns a version of the string.
Geoffrey Van Wyk
+1  A: 

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.

PreludeAndFugue
+4  A: 

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
Mark Byers
@mark Thanks. I should have known that!
Geoffrey Van Wyk