Python - how to replace string in a list?
python, python-2.7
Solution
If I understood you correctly, you want this:
trt = ['4' if word == '5' else word for word in trt]
If you need to do a lot of these replacements, you might want to define a map:
replacements = {
'5': '4',
'a': 'b',
}
trt = [replacements.get(word, word) for word in trt]
`get` looks up `word` in the `replacements` dict and returns `word` itself if it doesn't find such a key, or the corresponding value if it does.
Problem
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.