[英]How can I whitelist characters from a string in python 3?
我的問題很簡單,我正在嘗試從字符串中剝離任何非AZ或0-9的字符。
基本上,這是我要嘗試的過程:
whitelist=['a',...'z', '0',...'9']
name = '_abcd!?123'
name.strip(whitelist)
print(name)
>>> abcd123
重要的是要知道,我不能只在名稱中打印有效字符。 我需要實際使用處於更改狀態的變量。
您可以使用re.sub
並提供與您要刪除的內容完全匹配的模式:
import re
result = re.sub('[^a-zA-Z0-9]', '', '_abcd!?123')
輸出:
'abcd123'
將string
與列表理解一起使用
import string
whitelist = set(string.ascii_lowercase + string.digits)
name = ''.join(c for c in name if c in whitelist)
您可以使用簡單的正則表達式:
new_string = re.sub('[chars to remove]', '', old_string)
另請注意,字符串是不可變的。 您需要分配一個新變量才能進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.