str.capitalize()和str.title()之间的区别?

问题描述 投票:1回答:3

str.title()str.capitalize()有什么区别吗?我从文档中得出的理解是,这两种方法都将单词的第一个字母大写,而将其余字母都小写。有没有人遇到无法互换使用的情况?

python string methods case-sensitive title-case
3个回答
1
投票
>>> a = 'silly question' >>> a.title() 'Silly Question' >>> a.capitalize() 'Silly question' >>>

0
投票
>>> 'this is an example'.title() 'This Is An Example' >>> 'this is an example'.capitalize() 'This is an example'

0
投票
str.title()

返回字符串的标题大写形式,其中单词以大写字符,其余字符为小写。
For example: >>> >>> 'Hello world'.title() 'Hello World'

该算法使用一个与语言无关的简单定义作为一组连续的字母。该定义适用于许多但它意味着收缩和所有格中的撇号形成单词边界,这可能不是期望的结果:
https://docs.python.org/3/library/stdtypes.html

因此,在两种情况下,会有所不同:

[1)如果单词包含撇号,则撇号后面的字母将大写。

2)str.title()将句子的每个单词大写,而不仅仅是第一个单词。


0
投票
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' >>>
© www.soinside.com 2019 - 2024. All rights reserved.