前言
我們在處理字符串的時候别伏,總會遇到這種問題,一個字符串赔蒲,中間是我們想要的內(nèi)容泌神,兩邊會多出來一些內(nèi)容確定、數(shù)量不定字符舞虱,比如這樣:
str_sample = "-* This is a sample!\n###"
我希望去掉這個字符串兩頭的“-”欢际、“*”、“\n”矾兜、“#”以及“ ”损趋,只想保留"This is a sample!"
應(yīng)該怎么處理呢?
語法
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.當頭尾想去除的內(nèi)容不同時敞峭,只需要分別把我們希望去除的字符一次添加到參數(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!"
,應(yīng)該怎么操作呢缨伊?
>>> "-* This is a sample!\n###".strip("-* \n#")
'This is a sample!'