记录一些处理字符串的方法
原始字符串:x = “Life is short I choose python”
修改操作
-
整个字符串只有首字母大写:
x.capitalize()
输出:‘Life is short i choose python’
-
整个字符串所有字母小写(可以处理其他语言):
x.casefold()
输出:‘life is short i choose python’
-
每个元素的首字母都大写:
x.title()
输出:‘Life Is Short I Choose Python’
-
所有字母大小写翻转:
x.swapcase()
输出:‘lIFE IS SHORT i CHOOSE PYTHON’
-
所有字母小写(只能处理英语):
x.lower()
输出:‘life is short i choose python’
-
字符居中,填充两侧:
x.center(50,'1') #50表示输出长度,如果设置成了小于原字符串长度则输出原字符串; #'1'表示填充物,可以设置任何字符,没设置默认填充空格。
输出:‘1111111111Life is short I choose python11111111111’
-
字符串左对齐,填充右侧:
x.ljust(50,'1')
输出:‘Life is short I choose python111111111111111111111’
-
字符串右对齐,填充左侧:
x.rjust(50,'1')
输出:‘111111111111111111111Life is short I choose python’
查找操作
原始字符串:x = “上海自来水来自海上”
- 对某个元素在字符串内出现次数计数:
x<