Python之str内置函数
str.capitalize()
字串首字母大写
a_str = "hello World"
print("%s capitalized is %s" % (a_str, a_str.capitalize()))
str.casefold()
与lower()类似,将字串转换为小写,可用于大小写不敏感字串匹配
与lower()不同的是:lower方法只对ASCII编码,对于其他语言(非汉语或英文)可以使用casefold()进行大小写转换。
‘ß’是德语字符,其小写为’ss’
b_str = 'ß'
print("%s casefolded is %s" % (b_str, b_str.casefold()))
print("%s lower is %s" % (b_str, b_str.lower()))
-str.center(width[, fillchar])
返回指定宽度width,以当前字串居中的字串,左右不足部分以fillchar来填充, 如果width不大于原字串宽度,则返回原字串
if len(c_str) % 2 == 0 :
if len(c_str) + 1 == width:
do padding one fillchar on the left
else:
if len(c_str) + 1 == width:
do padding one fillchar on the right
c_str = 'abc'
print(c_str.center(4, '#'))
print(c_str.center(5, '#'))
c_str = 'icbc'
print(c_str.center(5, '#'))
print(c_str.center(6, '#'))
str.count(sub[, start[, end]])
返回子串出现频率
sub1 = "a"
sub2 = "ac"
sub3 = "a"
sub4 = "aa"
d_str = "abcdndiacac"
e_str = "aaaaa"
print(d_str.count(sub1)) print(d_str.count(sub2)) print(e_str.count(sub3)) print(e_str.count(sub4))
ljust(width[, fillchar])
使用指定字符填充,使字符串左对齐
c_str = "icbc"
# output: icbc$$
print(c_str.ljust(6, '$'))
rindex(sub[, start[, end]])
使用指定字符填充,使字符串右对齐
c_str = "icbc"
# output: $$icbc
print(c_str.rjust(6, '$'))
-zfill(width)
字符串右对齐,前面填充0,如果width小于原有子串长度,则返回原有子串
n_str = '98'
print(n_str.zfill(5))
n_str = '-98'
print(n_str.zfill(5))
n_str = '--98'
print(n_str.zfill(5))
n_str = '-98'
print(n_str.zfill(2))
# output:
# 00098
# -0098
# -0-98
# -98
https://docs.python.org/3/library/stdtypes.html?#str
还没有评论,来说两句吧...