字符串不仅支持所有通用序列操作,还实现了很多附件方法。
我会以『字符串方法』为标题,分几篇笔记逐一介绍这些方法。
我会在这仓库中持续更新笔记:https://github.com/orca-j35/python_notes
strip
🔨 str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The charsargument is a string specifying the set of characters to be removed. If omitted or None
, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
# 如果字符串左右两侧直接包含chars中的字符,则会移除这些字符
# chars的默认值是空白符
>>> ' spacious \t\n'.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:
# 遇到不属于chars的字符便会停止剥离
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
lstrip
🔨 str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None
, the charsargument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
rstrip
🔨 str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None
, the charsargument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:
>>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
网友评论