python中是否有任何字符串操作可以实现以下输入和输出? 如果我要使用正则表达式来替换子字符串,正则表达式会是什么样子?
#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
我认为这应该可以解决问题:
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 的答案更简单,并且不需要使用 regex。
如果这些是唯一的破折号:
z = x.replace('-', ' ').replace(y.replace('-', ' '), y)