Python 中的 String.capwords() 方法
string.capwords
方法:
- 使用 str.split() 方法将字符串拆分为单词。
- 使用 str.capitalize() 方法将每个单词大写。
- 使用 str.join() 方法将大写单词连接成字符串。
from string import capwords
my_str = 'zadmei www com'
result = capwords(my_str)
print(result) # ?️ 'Zadmei Www Com'
string.capwords()
方法将每个单词中的第一个字符转换为大写,其余的转换为小写。
from string import capwords
my_str = 'ZADMEI WWW COM'
result = capwords(my_str)
print(result) # ?️ 'Zadmei Www Com'
如果我们需要将列表中每个单词的首字母大写,也可以使用 capwords()
方法。
from string import capwords
my_list = ['bobby hadz', 'dot com']
result = [capwords(item) for item in my_list]
print(result) # ?️ ['Bobby Hadz', 'Dot Com']
我们使用列表推导来迭代列表并将每个项目传递给 capwords()
方法。
string.capwords()
方法对字符串中的每个单词使用 str.capitalize() 方法。
tr.capitalize
函数返回字符串的副本,其中第一个字符大写,其余字符小写。
print('zadmei'.capitalize()) # ?️ 'Zadmei'
print('WWW'.capitalize()) # ?️ 'Www'
请注意,还有一个 str.title()
方法。
str.title
方法返回字符串的标题版本,其中单词以大写字符开头,其余字符为小写。
my_str = 'zadmei www'
result = my_str.title()
print(result) # ?️ "Zadmei Www"
但是,该算法还将撇号后的字符转换为大写。
my_str = "it's him"
result = my_str.title()
print(result) # ?️ "It'S Him"
string.capwords
方法没有这个问题,因为它只在空格上分割字符串。
from string import capwords
my_str = "it's him"
result = capwords(my_str)
print(result) # ?️ "It's Him"
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。