The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Question
00:49 Accepted answer (Score 7)
01:11 Answer 2 (Score 8)
01:33 Answer 3 (Score 3)
01:49 Answer 4 (Score 1)
02:15 Thank you

--

Full question
https://stackoverflow.com/questions/3344...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string

#avk47



ANSWER 1

Score 8


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



ACCEPTED ANSWER

Score 7


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



ANSWER 3

Score 3


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

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




ANSWER 4

Score 1


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.