Python字符串的常用操作 — 大小写转换

会产生新的字符串对象

upper()把字符串中所有的字符都转成大写字母
lower()把字符串中所有的字符都转成小写字母
swapcase()把字符串中所有的大写字母转换成小写字母,所有的小写字母转换成大写字母,相当于反转
captitalize()把字符串的第一个字符转成大写,其余的字符都转成小写
title()把字符串中每个单词的第一个字符都转成大写,再把每个单词剩余的字符转成小写

1、upper() 把字符串中所有的字符都转成大写字母

str1 = 'hello,Python'

str2 = str1.upper()

print(str1,id(str1))    #hello,Python 2447710550576
print(str2,id(str2))    #HELLO,PYTHON 2447710549040

2、lower() 把字符串中所有的字符都转成小写字母

str1 = 'hELLo,Python'

str2 = str1.lower()

print(str1,id(str1))    #hELLo,Python 2734199732336
print(str2,id(str2))    #hello,python 2734199761840

3、swapcase()

把字符串中所有的大写字母转换成小写字母,所有的小写字母转换成大写字母,相当于反转

str1 = 'hELLo,Python'

str2 = str1.swapcase()

print(str1,id(str1))    #hELLo,Python 2943579650352
print(str2,id(str2))    #HellO,pYTHON 2943579679664

4、captitalize() 把字符串的第一个字符转成大写,其余的字符都转成小写

str1 = 'hELLo,Python'

str2 = str1.capitalize()

print(str1,id(str1))    #hELLo,Python 2199094685296
print(str2,id(str2))    #Hello,python 2199094717616

5、title() 把字符串中每个单词的第一个字符都转成大写,再把每个单词剩余的字符转成小写

str1 = 'hello,pyTHon and woRld'

str2 = str1.title()

print(str1,id(str1))    #hello,pyTHon and woRld 1819334165008
print(str2,id(str2))    #Hello,Python And World 1819334173648
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容