str.title()
与str.capitalize()
有什么区别吗?我从文档中得出的理解是,这两种方法都将单词的第一个字母大写,而将其余字母都小写。有没有人遇到无法互换使用的情况?
>>> a = 'silly question'
>>> a.title()
'Silly Question'
>>> a.capitalize()
'Silly question'
>>>
>>> 'this is an example'.title()
'This Is An Example'
>>> 'this is an example'.capitalize()
'This is an example'
str.title()
返回字符串的标题大写形式,其中单词以大写字符,其余字符为小写。For example: >>> >>> 'Hello world'.title() 'Hello World'
该算法使用一个与语言无关的简单定义作为一组连续的字母。该定义适用于许多但它意味着收缩和所有格中的撇号形成单词边界,这可能不是期望的结果:https://docs.python.org/3/library/stdtypes.html因此,在两种情况下,会有所不同:
[1)如果单词包含撇号,则撇号后面的字母将大写。
2)
str.title()
将句子的每个单词大写,而不仅仅是第一个单词。
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> "two words".title()
'Two Words'
>>> "two words".capitalize()
'Two words'
>>>