Python 字符串相关的操作函数
【摘要】 Python基础之字符串的相关函数解析
1.0 capitalize()函数
描述:将字符串的第一个字母变成大写,其余字母变为小写。
语法:str.capitalize() —> str 返回字符串
程序示例:
str1 = "on the long road to success"
str2 = " on the long road to success" #字母i前有空格
str3 = "On the long road to success"
print(str1.capitalize())
print(str2.capitalize())
print(str3.capitalize())
程序运行结果:
/home/yuchuanpc/Python/PythonProject/venv/bin/python /home/yuchuanpc/Python/PythonProject/YuchuanTest01.py
On the long road to success
on the long road to success
On the long road to success
2.0 title()函数
描述:返回一个满足标题格式的字符串。即所有英文单词首字母大写,其余英文字母小写。
语法:str.title() -> str 返回一个字符串
程序示例:
str1 = "on the long road to success"
str2 = " on the long road to success" #字母i前有空格
str3 = "On the long road to success"
print(str1.title()) #将字符串str的所有单词首字母大写,其余字母小写
print(str2.title()) #将字符串str的所有单词首字母大写,其余字母小写
print(str3.title()) #将字符串str的所有单词首字母大写,其余字母小写
程序运行结果:
On The Long Road To Success
On The Long Road To Success
On The Long Road To Success
3.0 swapcase()函数
描述:将字符串str中的大小写字母同时进行互换。即将字符串str中的大写字母转换为小写字母,将小写字母转换为大写字母。
语法:str.swapcase() -> str 返回字符串
程序示例:
str1 = "on the long road to success"
str2 = "on the long road to success,几度艰辛,几多伤痛。" #字母i前有空格
str3 = "On THE Long Road TO " #将字符串str1中的大写字母转为小写字母,小写字母转换为大写字母。
print(str1.swapcase())
print(str2.swapcase())
print(str3.swapcase())
程序运行结果:
ON THE LONG ROAD TO SUCCESS
ON THE LONG ROAD TO SUCCESS,几度艰辛,几多伤痛。
oN the lONG rOAD to
4.0 lower()函数
描述:将字符串中的所有大写字母转换为小写字母。
语法:str.lower() -> str 返回字符串
程序示例:
str1 = "On THE Long Road TO "
str2 = "Groß - α" #德语 大写α
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())
程序运行结果:
on the long road to
on the long road to
gross - α
groß - α
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
君莫笑vs叶修2020/03/28 07:36:251楼编辑删除举报