Saturday, 17 August 2013

Python - how to replace string in a list?

Python - how to replace string in a list?

Noob here. I can't seem to find satisfactory solution to this and I've
been searching all day.
The script I'm writing generates a list called "trt" full of strings. Some
of those strings may need to be replaced before the list is processed
further. For instance, string "5" needs to be replaced with "4", but
without messing with strings such as "-5" or "5*". The solution must not
change the order of strings in the list "trt" or enter any new character
or blank space in the list.
I've already tried to do it like this:
trt = [word.replace('5','4') for word in trt]
but it is not a good solution, as it affects "5*" and makes the script
misbehave.

No comments:

Post a Comment