如何輕松地用下劃線替換特殊字符和空格_,但也可以用單個下劃線替換多個下劃線_?
我的方法如下,但它并不漂亮。
import string
s = 'Hi th@re gu^ys!@#()tes t;"[]ing'
for chr in string.punctuation string.whitespace:
s = s.replace(chr, '_')
while '__' in s:
s = s.replace('__', '_')
print(s) # Hi_th_re_gu_ys_tes_t_ing
第 2 條:
dont_want_these = frozenset(string.punctuation string.whitespace)
def repl_it(s):
chrs = list(s)
prev_chr_was_fail = False
for i, chr in enumerate(chrs):
if chr in dont_want_these:
if prev_chr_was_fail:
chrs[i] = ''
else:
prev_chr_was_fail = True
chrs[i] = '_'
else:
prev_chr_was_fail = False
return ''.join(chrs)
assert repl_it('Hi th@re gu^ys!@#()tes t;"[]ing') == 'Hi_th_re_gu_ys_tes_t_ing'
謝謝
uj5u.com熱心網友回復:
import re
new_s1 = re.sub(r'[\W_] ','_',s1)
new_s2 = re.sub(r'[\W_] ','_',s2)
輸入:
s1 = 'Hi th@re gu^ys!@#()tes t;"[]ing'
s2 = 'Hi th@re gu^ys!@#()tes t___;"[]ing'
輸出:
>>> print(new_s1)
>>> Hi_th_re_gu_ys_tes_t_ing
>>> print(new_s2)
>>> Hi_th_re_gu_ys_tes_t_ing
uj5u.com熱心網友回復:
import re
s = 'Hi th@re gu^ys!@#()tes t;"[]ing'
new_s = re.sub(r'[\W] ','_',s)
print(new_s)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485664.html
