简体   繁体   English

用n之间的破折号替换某个子字符串-python

[英]Replace a certain substring with dashes in betweenn - python

Is there any string manipulation in python that can achieves the following input and output? python中是否有任何字符串操作可以实现以下输入和输出? If i'm going to use regex how would the regex expression look like to replace the substring? 如果我要使用正则表达式,正则表达式将如何替换子字符串?

#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

I think this should do the trick: 我认为这应该可以解决问题:

y='sentence-with-dashes'
x='this is a sentence with dashes'
r=re.compile(re.escape(y).replace('\\-','[- ]'))
z=re.sub(r,y,x)

this won't touch any hyphens that appear outside the y value, if you don't care about this then eumiro's answer is simpler, and doesn't require the use of regex. 这不会碰到y值以外的任何连字符,如果您对此不关心,那么eumiro的答案就更简单了,并且不需要使用正则表达式。

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

z = x.replace('-', ' ').replace(y.replace('-', ' '), y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM