python中是否有任何字符串操作可以实现以下输入和输出?如果我要使用正则表达式,那么regex表达式将如何替换子字符串?
#inputs
y = sentence-with-dashes
x = this is a sentence with dashes
#output
z = this is a sentence-with-dashes
#####################################
#sometimes the input is pretty messed up like this
y = sentence-with-dashes
x = this is a sentence-with dashes
#output
z = this is a sentence-with-dashes
答案 0 :(得分:3)
我认为这应该可以解决问题:
y='sentence-with-dashes'
x='this is a sentence with dashes'
r=re.compile(re.escape(y).replace('\\-','[- ]'))
z=re.sub(r,y,x)
这不会触及任何出现在y
值之外的连字符,如果你不关心这个,那么eumiro的答案就更简单了,并且不需要使用正则表达式。
答案 1 :(得分:1)
如果这些是唯一的破折号:
z = x.replace('-', ' ').replace(y.replace('-', ' '), y)