前言
我們在處理字符串的時候,總會遇到這種問題,一個字符串,中間是我們想要的內容,兩邊會多出來一些內容確定、數(shù)量不定字符,比如這樣:
str_sample = "-* This is a sample!\n###"
我希望去掉這個字符串兩頭的“-”、“*”、“\n”、“#”以及“ ”,只想保留"This is a sample!"應該怎么處理呢?
語法
str.strip([chars])
官方解釋:
Return a copy of the string with the leading and trailing characters removed. The chars argument 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參數(shù)是一個字符串,指定要刪除的字符集。如果省略或沒有,chars參數(shù)默認為刪除空格。chars參數(shù)不是前綴或后綴;相反,它的值的所有組合都被剝離。
參數(shù)與示例
- 參數(shù)可以為空,表示去掉頭尾的空格。
>>> ' spacious '.strip()
'spacious'
- 當我們想去除的字符出現(xiàn)了多次,參數(shù)中只需要輸入一次我們想去除的字符即可。
>>> "###crystal".strip("#")
'crystal'
>>>
3.當頭尾想去除的內容不同時,只需要分別把我們希望去除的字符一次添加到參數(shù)中即可。
>>> 'www.example.com'.strip('cmowz.')
'example'
- 參數(shù)為“cmowz.”。我們發(fā)現(xiàn),這個
'www.example.com'字符串,頭的"w"和".",尾的"c"、"o"、"m"和"."都被去除了,且我們輸入?yún)?shù)時,不需要按照順序輸入。
最后
前言中的str_sample = "-* This is a sample!\n###",我們希望提取"This is a sample!",應該怎么操作呢?
>>> "-* This is a sample!\n###".strip("-* \n#")
'This is a sample!'