0

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
4

2 回答 2

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 的答案会更简单,并且不需要使用正则表达式。

于 2012-09-17T07:25:59.880 回答
1

如果这些是唯一的破折号:

z = x.replace('-', ' ').replace(y.replace('-', ' '), y)
于 2012-09-17T07:24:37.440 回答