[英]Replace a certain substring with dashes in betweenn - python
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的答案就更简单了,并且不需要使用正则表达式。
如果这些是唯一的破折号:
z = x.replace('-', ' ').replace(y.replace('-', ' '), y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.