python字符串操作--title()方法将每个单词改为标题形式

title() 方法用于将每个单词的第一个字符大写,其余小写

格式及参数

1
str.title()

str : 字符串对象

参考资料

实例(3.8.8)

1
2
3
4
5
str = 'gao yuan qi'

print(str.title())
# 原有对象没有改变
print(str)

title-1

补充

title() 方法将连续的字母组合视为单词,意味着代表缩写形式与所有格的撇号也会成为单词边界,例如 It's

1
2
3
str = "It's not always smooth sailing on the road to learning"

print(str.title())

title-2

使用正则表达式来解决撇号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import re

phrases = "It's not always smooth sailing on the road to learning"

def titlecase(str):

title = re.sub(
r"[A-Za-z]+('[A-Za-z]+)?",
lambda mo: mo.group(0).capitalize(),
str
)

return title

print(titlecase(phrases))

title-3