我有一个包含数字的字符串,我们需要删除所有不是数字的字符,并用#
替换数字我写了一个正则表达式,它可以用#替换数字,但是找不到正则表达式来删除不是数字的字符。
import re
def replace_digits(string):
m=re.sub("\d","#",string)
示例:
234
-> ###
a2b3c4
-> ###
abc
-> <empty string>
#2a$#b%c%561#
-> ####
答案 0 :(得分:2)
import re
examples = ['234',
'a2b3c4',
'abc',
'#2a$#b%c%561#']
for example in examples:
new_s = '#' * len(re.sub(r'\D', '', example))
print('Input = {} Output = {}'.format(example, new_s))
打印:
Input = 234 Output = ###
Input = a2b3c4 Output = ###
Input = abc Output =
Input = #2a$#b%c%561# Output = ####
编辑(不使用正则表达式-感谢@CorentinLimier)
for example in examples:
new_s = ''.join('#' for c in example if c.isdigit())
print('Input = {} Output = {}'.format(example, new_s))
编辑(在评论中添加@Tomerikoo的答案):
for example in examples:
new_s = '#' * len([x for x in example if x.isdigit()])
print('Input = {} Output = {}'.format(example, new_s))