为什么istitle()字符串方法在明显是标题格式时返回false?
在Python 2.6.5的手册中,关于istitle()
这个字符串方法是这么说的:
如果这个字符串是标题格式的,并且至少有一个字符,就返回真。标题格式的意思是大写字母只能跟在小写字母后面,而小写字母只能跟在大写字母后面。如果不符合这些条件,就返回假。
但是在这个例子中,它返回的是假:
>>> book = 'what every programmer must know'
>>> book.title()
'What Every Programmer Must Know'
>>> book.istitle()
False
我漏掉了什么呢?
4 个回答
3
可能是因为你还在对原始的书籍对象使用 istitle() 方法。
试试用 book.title().istitle() 这个方式……
8
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
7
title()这个方法不会改变原来的字符串(在Python中,字符串是不可变的)。它会创建一个新的字符串,你需要把这个新字符串赋值给你的变量:
>>> book = 'what every programmer must know'
>>> book = book.title()
>>> book.istitle()
True