【问题标题】:Why does the istitle() string method return false if the string is clearly in title-case?如果字符串明显是标题大小写,为什么 istitle() 字符串方法返回 false?
【发布时间】:2010-07-27 13:40:00
【问题描述】:

istitle() 字符串方法中,Python 2.6.5 手册中写道:

如果字符串是标题大小写的字符串并且至少有一个字符,则返回 true,例如,大写字符只能跟在非大小写字符后面,小写字符只能跟在大小写字符后面。否则返回 false。

但在这种情况下它返回 false:

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

我错过了什么?

【问题讨论】:

    标签: python string


    【解决方案1】:

    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
    

    【讨论】:

    • 好的,这就是我所缺少的!谢谢。文档实际上确实说 .title() 返回字符串的一个版本。
    【解决方案2】:

    方法 title() 不会改变字符串(字符串在 Python 中是不可变的)。它会创建一个新字符串,您必须将其分配给您的变量:

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

    【讨论】:

    • 谢谢。我早该知道的!
    【解决方案3】:

    可能是因为你还在原书上调用 istitle()。

    尝试 book.title().istitle() 代替......

    【讨论】:

      【解决方案4】:

      执行以下操作:

      print book
      

      在您执行book.title() 之后。你会看到book 没有改变。

      原因是book.title() 创建了一个新字符串。名称book 仍指原始字符串。

      【讨论】:

        猜你喜欢
        • 2014-10-10
        • 2017-12-14
        • 2020-09-24
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        相关资源
        最近更新 更多