假设我有一个字符串
the_string = "the brown fox"
我不想用多个字符替换空格,例如,5个破折号
new_string = "the-----brown-----fox"
但这将是一个变量,所以我不能这样做:
the_string = 'the brown fox'
new_string = re.sub(r'\s', '-----', the_string)
我需要以下内容:
the_string = 'the brown fox'
num_dashes = 5
new_string = re.sub(r'\s', r'-{num_dashes}', the_string)
这样的事情可能吗?
答案 0 :(得分:3)
是的,你可以这样做:
the_string = 'the brown fox'
num_dashes = 5
re.sub(r'\s', '-'*num_dashes, the_string)
答案 1 :(得分:1)
def repl(matchobj):
if matchobj.group():
#do something
#return whatever you want to replace
my_str = "the brown fox"
pattern = r"\s+"
print re.sub(pattern, repl, my_str)
您可以在re.sub