Why istitle () string method returns false if the string explicitly has a header?

From the string method istitle(), the Python 2.6.5 manual says:

Returns true if the string is a title bar and there is at least one character, for example, uppercase characters can only follow uncommitted characters, and lowercase letters can only be truncated. Otherwise, returns false.

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
source share
4 answers

The method name () does not mutate the string (strings are immutable in Python). It creates a new line that you must assign to your variable:

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

book.title() book. .

>>> 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
+8

Perhaps because you are still calling istitle () in the original book.

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

+3
source

Follow these steps:

print book

after completion book.title(). You will see what has booknot changed.

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

+1
source

Source: https://habr.com/ru/post/1756753/


All Articles