0

I have a string:

string = '17 121221 17 17939 234343 17 39393'

How do I make sure that when using string.replace('17', 'sth') only the 17s are replaced (but not 17 which is a part of 17939)?

I would like an output string like:

string = 'sth 121221 sth 17939 234343 sth 39393'

Cheers, Kate

3
  • @RajeshKumar, That fails with 123 345 12317 1234 since it also replaces the 17 in 12317 which the OP doesn't want Commented May 20, 2014 at 7:25
  • @sshashank124 it actually works if I do string.replace(' 17 ', 'sth')! Commented May 20, 2014 at 7:31
  • But that would fail if 17 is at the start and end of the string Commented May 20, 2014 at 7:31

2 Answers 2

3

You can accomplish that using regex:

import re

string = '17 121221 17 17939 234343 17 39393'

>>> print re.sub(r'(\D|^)17(\D|$)', r'\1sth\2', string)
sth 121221 sth 17939 234343 sth 39393
Sign up to request clarification or add additional context in comments.

1 Comment

this is going to fail when there's a number "-17" in the string, and in a few other cases as well.
1

much easier to use and fail-proof:

>>> string = '17 121221 17 17939 234343 17 39393'
>>> ' '.join( 'sth' if i == '17' else i for i in string.split() )
'sth 121221 sth 17939 234343 sth 39393'

you should not use regex when a simple split/join is sufficient.

Comments

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.