alvas
alvas

Reputation: 122022

Replace a certain substring with dashes in betweenn - python

Is there any string manipulation in python that can achieves the following input and output? 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

Upvotes: 0

Views: 977

Answers (2)

codebox
codebox

Reputation: 20254

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.

Upvotes: 3

eumiro
eumiro

Reputation: 212835

If these are the only dashes:

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

Upvotes: 1

Related Questions