從字串中刪除不需要的前導字元
提供了三種方法,可以從字串中刪除前導和尾隨字元:str.strip,str.rstrip 和 str.lstrip。所有三種方法都具有相同的簽名,並且所有三種方法都返回一個新的字串
str.strip([chars])
str.strip 作用於給定的字串並刪除(剝離)引數 chars 中包含的任何前導或尾隨字元; 如果未提供 chars 或者是 None,則預設情況下會刪除所有空白字元。例如:
>>> " a line with leading and trailing space ".strip()
'a line with leading and trailing space'
如果提供了 chars,則會從字串中刪除其中包含的所有字元,並返回該字串。例如:
>>> ">>> a Python prompt".strip('> ') # strips '>' character and space character
'a Python prompt'
str.rstrip([chars]) 和 str.lstrip([chars])
這些方法與 str.strip() 具有相似的語義和引數,它們的區別在於它們的起始方向。str.rstrip() 從字串的結尾開始,而 str.lstrip() 從字串的開頭分割。
例如,使用 str.rstrip:
>>> " spacious string ".rstrip()
' spacious string'
同時,使用 str.lstrip:
>>> " spacious string ".rstrip()
'spacious string '