2

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.

4
  • You need to use regex. See re module. Commented Aug 17, 2013 at 19:55
  • and makes the script misbehave. Define 'misbehave'? Commented Aug 17, 2013 at 19:55
  • 1
    Can you provide us with sample input and expected output? Commented Aug 17, 2013 at 19:56
  • @RohitJain He doesn't need regex, he's replacing strings in a list, not substrings in a string. Commented Aug 17, 2013 at 19:59

3 Answers 3

9

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.

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

1 Comment

You, sir, are full of win.
1

word.replace('5','4') replaces each 5 in the string word with a 4. This is not what you want to do (I don't think).

One solution:

for index, value in enumerate(trt):
    if value == "5":
        trt[index] = "4"

A more functional solution:

 trt = [i if i != "5" else "4" for i in trt]

1 Comment

the first solution makes more sense haha
0

Here is a one-line lambda:

newlst = list(map(lambda x: '4' if x in ['5'] else x,lst))

Assume this is your list:

lst = ['-5','5*','5','-5','5']

Then:

newlst = list(map(lambda x: '4' if x in ['5'] else x,lst))

Returns:

['-5', '5*', '4', '-5', '4']

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.