有没有比“title”更好的字符串方法来大写字符串中的每个单词?

2024-10-03 11:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

即使撇号后面的字母也要大写,这不是预期的结果

>>> test = "there's a need to capitalize every word"
>>> test.title()
"There'S A Need To Capitalize Every Word"

有些人建议使用capwords,但capwords似乎有缺陷(仅 大写单词前面加空格)。在这种情况下,我还需要能够大写由句点分隔的单词(例如:一、二、三结果应该是一、二、三). 在

有没有一种方法在capwords和title中不会失败?在


Tags: totesttitle字母need单词wordthere
3条回答

在python的文档中有一个解决问题的方法,here

>>>
>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...

您可以在re.sub的替换部分使用匿名函数

>>> import re
>>> test = "there's a need to capitalize every word"
>>> re.sub(r'\b[a-z]', lambda m: m.group().upper(), test)
"There'S A Need To Capitalize Every Word"

使用string.capwords

import string
string.capwords("there's a need to capitalize every word")

相关问题 更多 >