字符串的方法、注释及示例2.
ljust(width) 返回一个左对齐的字符串,并使用空格填充至长度为 width 的新字符串。/dʒʌst/ adj. 公正的,合理的;正直的,正义的;正确的;公平的;应得的 adv. 只是,仅仅;刚才,刚刚;正好,恰好;实在;刚要
>>> str1 = 'python' >>> str1.ljust(20,'0') 'python00000000000000'
lstrip() 去掉字符串左边的所有空格。
>>> str1 = ' Python' >>> str1.lstrip() 'Python'
partition(sub) 找到子字符串 sub,把字符串分成一个 3 元组 (pre_sub, sub, fol_sub),如果字符串中不包含 sub 则返回 ('原字符串', '', '') /pɑr'tɪʃən/ n. 划分,分开
>>> str1 = 'python' >>> str1.partition('z') ('python', '', '') >>> str1.partition('t') ('py', 't', 'hon')
replace(old, new[, count]) 把字符串中的 old 子字符串替换成 new 子字符串,如果 count 指定,则替换不超过 count 次。 /rɪ'ples/ vt. 取代,代替;替换,更换;归还,偿还;把…放回原处
>>> str1 = 'ababababab' >>> str1.replace('a','s',4) 'sbsbsbsbab'
rfind(sub[, start[, end]]) 类似于 find() 方法,不过是从右边开始查找。
rindex(sub[, start[, end]]) 类似于 index() 方法,不过是从右边开始。
rjust(width) 返回一个右对齐的字符串,并使用空格填充至长度为 width 的新字符串。和ljust()类似。
rpartition(sub) 类似于 partition() 方法,不过是从右边开始查找。
rstrip() 删除字符串末尾的空格。
split(sep=None, maxsplit=-1) 不带参数默认是以空格为分隔符切片字符串,如果 maxsplit 参数有设置,则仅分隔 maxsplit 个子字符串,返回切片后的子字符串拼接的列表。
/splɪt/ n. 劈开;裂缝 adj. 劈开的 vt. 分离;使分离;劈开;离开;分解 vi. 离开;被劈开;断绝关系
>>> str1 = 'Change the world by program.' >>> str1.split() ['Change', 'the', 'world', 'by', 'program.'] >>> str1.split('e') ['Chang', ' th', ' world by program.']
splitlines(([keepends])) 在输出结果里是否去掉换行符,默认为 False,不包含换行符;如果为 True,则保留换行符。/splɪt/ /lainz/ n. 线;台词;航线(line的复数)
v. 排成一行;画线于(line的三单形式)
>>> str1 = 'Change \nthe \nworld \nby \nprogram.' >>> str1 'Change \nthe \nworld \nby \nprogram.' >>> print(str1) Change the world by program. >>> str1.splitlines() ['Change ', 'the ', 'world ', 'by ', 'program.'] >>> str1 = 'Change the world by program.' >>> str1.splitlines() ['Change the world by program.']
startswith(prefix[, start[, end]]) 检查字符串是否以 prefix 开头,是则返回 True,否则返回 False。start 和 end 参数可以指定范围检查,可选。/stɑrt/ vt. 开始;启动.
/swɪθ/ adv. 立刻,迅速地
>>> str1 = 'Change the world by program.' >>> str1.startswith('C') True >>> str1.startswith('C',10,15) False
strip([chars]) 删除字符串前边和后边所有的空格,chars 参数可以定制删除的字符,可选。 /strɪp/
>>> str1 = ' abcdefgabc ' >>> str1.strip() 'abcdefgabc' >>> str1.strip('a') ' abcdefgabc ' >>> str2 = 'aaabbbcccaaa' >>> str2.strip('a') 'bbbccc' >>> str3 = 'aaabbbccc' >>> str3.strip('a') 'bbbccc'
swapcase() 翻转字符串中的大小写。 /swɑp/ v. 交换,调换;交易;以……作交换;代替 /kes/ n. 情况;实例;箱
>>> str1 = 'PYthon' >>> str1.swapcase() 'pyTHON'
upper() 转换字符串中的所有小写字符为大写。
title() 返回标题化(所有的单词都是以大写开始,其余字母均小写)的字符串。
translate(table) 根据 table 的规则(可以由 str.maketrans('a', 'b') 定制)转换字符串中的字符。 /træns'let/ vt. 翻译;转化;解释;转变为;调动
>>> str3 = 'aaabbbccc' >>> str3.translate(str.maketrans('a', 's') ) 'sssbbbccc'
zfill(width) 返回长度为 width 的字符串,原字符串右对齐,前边用 0 填充。
参考:https://fishc.com.cn/thread-38992-1-1.html