0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

don't forget to add \b where appropriate
That won't work if y contains anything with special meaning to regular expressions. Try r=re.compile(re.escape(y).replace('\\-','[- ]')) to protect any non alphanumeric characters.
You missed that the hyphen also gets escaped so you have to escape it in the replace call (so I edited it for you).
1

If these are the only dashes:

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

2 Comments

This works fine for he OP's example, but I can see it gets fun where x = 'ooops - a sentence-with dashes' and the result is z == 'ooops a sentence-with-dashes' (<- there is a double space in there...)...
@JonClements - yes, that's why I wrote "if these are the only dashes" . With more dashes it does not work properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.