4.7 字符串常用操作——其他函数

更新于 2026年10月13日 版权声明
4.7 字符串常用操作——其他函数

①capitalize():将字符串第一个字符转换成大写。

= "hello world and hbes and hbeszy and Python"
# 结果:Hello world and hbes and hbeszy and python
print(mystr.capitalize())

注意:capitalize()函数转换后,只有字符串第一个字符大写,其他的字符全都小写。

②title():将字符串每个单词的首字母转换成大写。

mystr = "hello world and hbes and hbeszy and Python"
# 结果:Hello World And Hbes And Hbeszy And Python
print(mystr.title())

③lower():将字符串中的大写转小写。

mystr = "hello world and hbes and hbeszy and Python"
# 结果:hello world and hbes and hbeszy and python
print(mystr.lower())

④upper():将字符串中小写转大写。

mystr = "hello world and hbes and hbeszy and Python"
# 结果:HELLO WORLD AND HBES AND HBESZY AND PYTHON
print(mystr.upper())

⑤lstrip():删除字符串左侧空白字符。

mystr = "    hello world and hbes and hbeszy and Python"
# 结果:hello world and hbes and hbeszy and Python
print(mystr.lstrip())

⑥rstrip():删除字符串右侧空白字符。(https://www.daowen.com)

mystr = "    hello world and hbes and hbeszy and Python   "
# 结果:空格原样输出world and hbes and hbeszy and Python
print(mystr.rstrip())

⑦strip():删除字符串两侧空白字符。

mystr = "    hello world and hbes and hbeszy and Python   "
# 结果:world and hbes and hbeszy and Python
print(mystr.strip())

⑧ljust():返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。

字符串序列.ljust(长度, 填充字符)

mystr = "hello"
# 结果:hello.....
print(mystr.ljust(10,'.'))
# 结果:hello空格
print(mystr.ljust(10))

⑨rjust():返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同。

mystr = "hello"
# 结果:.....hello
print(mystr.rjust(10,'.'))
# 结果:空格hello
print(mystr.rjust(10))

⑩center():返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同。

mystr = "hello"
# 结果:..hello...
print(mystr.center(10,'.'))
# 结果:空格hello空格
print(mystr.center(10))

✍AI写作