답변:
구조에 정규식!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
예:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
re.sub("[\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+", " ", ":%# unicode ΣΘΙП@./\n")
import re; regex = re.compile('[^0-9a-zA-Z]+'); regex.sub('*', 'h^&ell.,|o w]{+orld')
\W비 단어 문자에 대한 것입니다. 거의 동일하지만 밑줄을 단어 문자로 사용할 수 있습니다 (이유를 모릅니다) : docs.python.org/3.6/library/re.html#index-32
사용 \W하는 것과 같습니다 [^a-zA-Z0-9_]. https://docs.python.org/2/library/re.html 문서를 확인하십시오.
Import re
s = 'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'
업데이트 :이 솔루션은 밑줄도 제외합니다. 알파벳과 숫자 만 제외하려면 nneonneo의 솔루션이 더 적합합니다.
\W로 동일합니다[^a-zA-Z0-9_] 파이썬 2.x 또는 3.0 만 Python 3.x에서는 / 플래그가 사용되는 경우에만 \W+동일합니다 . [^a-zA-Z0-9_]re.ASCIIre.A