[英]How do I strip a string given a list of unwanted characters? Python
有沒有辦法在python str.strip()
列表而不是char傳遞給str.strip()
? 我一直在這樣做:
unwanted = [c for c in '!@#$%^&*(FGHJKmn']
s = 'FFFFoFob*&%ar**^'
for u in unwanted:
s = s.strip(u)
print s
期望的輸出,這個輸出是正確的,但應該有一種比我上面編碼更優雅的方式:
oFob*&%ar
Strip和friends采用表示一組字符的字符串,因此您可以跳過循環:
>>> s = 'FFFFoFob*&%ar**^'
>>> s.strip('!@#$%^&*(FGHJKmn')
'oFob*&%ar'
(這方面的缺點是像fn.rstrip(".png")
這樣的東西似乎適用於許多文件名,但實際上並不起作用)
因為,您希望不從中間刪除元素,您可以使用。
>>> 'FFFFoFob*&%ar**^'.strip('!@#$%^&*(FGHJKmn')
'oFob*&%ar'
否則,使用str.translate()
。
>>> 'FFFFoFob*&%ar**^'.translate(None, '!@#$%^&*(FGHJKmn')
'oobar'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.