Python---字符串第一篇
1.capitalize
将首字母变大写,其余字母强行变为小写。
test = "alex"
v = test.capitalize()
print(v)
结果为Alex
test = "aLEX"
v = test.capitalize()
print(v)
结果为Alex
2.casefold
Python casefold() 方法是Python3.3版本之后引入的,其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。
两者的区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。
test = "aLEX"
v1 = test.casefold()
print(v1)
结果为alex
3.center
center() 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
str.center(width[, fillchar])
-
width -- 字符串的总宽度。
-
fillchar -- 填充字符。
test = "aLEX"
v = test.center(20)
print(v)
结果为 aLEX
test = "aLEX"
v1 = test.center(20,'*')
print(v1)
结果为********aLEX********
4. ljust,rjust
ljust返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串,rjust则相反。
test = "leslie"
v = test.ljust(20,"*")
print(v)
结果为 leslie**************
test = "leslie"
v = test.rjust(20,"*")
print(v)
结果为 **************leslie
5.count
count(self, sub, start=None, end=None)
在字符串中找子序列出现的次数,start表示起始位置,end表示终止位置。
test = "aLEaXa"
v = test.count('a')
print(v)
结果为3
test = "aLEaXa"
v1 = test.count('a',2)
print(v1)
结果为2
6.startswith,endswith
endswith(self, suffix, start=None, end=None)
startswith(self, prefix, start=None, end=None)
startswith判断字符串以什么开头
endswith判断字符串以什么结尾
test = "aLEaXa"
v = test.endswith('a')
print(v)
结果为True
v1 = test.startswith('L')
print(v1)
结果为False

浙公网安备 33010602011771号