kate88
kate88

Reputation: 371

Replace strings in Python

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

Upvotes: 0

Views: 75

Answers (2)

lenik
lenik

Reputation: 23556

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.

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

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

Upvotes: 3

Related Questions