maudev
maudev

Reputation: 1101

Replace two values in a list using list comprehension?

I have thw following list:

list1 = ["cmd_%Y","cmd_%y","cmd_other"]

I need to replace "%y" and "%Y" (uppercase and lowercase) using list comprehensions, I tried just for one substr:

list1 = [ cmd.replace('%Y', "some_val_forY") for cmd in list1 ]

And obviously I'm discarding non-pythonic way to solve this issue.

How can I modify my solution to acept both criteria and get:

list1 = [ "cmd_some_val_for_Y","cmd_some_val_for_y", "cmd_other" ]

Upvotes: 1

Views: 45

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

In most simple case - with chained replacement:

list1 = ["cmd_%Y","cmd_%y","cmd_other"]
list1 = [cmd.replace('%Y', "some_val_Y").replace('%y', "some_val_y") for cmd in list1]
print(list1)   # ['cmd_some_val_Y', 'cmd_some_val_y', 'cmd_other']

Otherwise, use regex substitution:

import re

list1 = ["cmd_%Y","cmd_%y","cmd_other"]
pat = re.compile(r'%y', re.I)
list1 = [pat.sub(lambda m: 'some_val_y' if m.group() == '%y' else 'some_val_Y', cmd) 
         for cmd in list1]

print(list1)   # ['cmd_some_val_Y', 'cmd_some_val_y', 'cmd_other']

Upvotes: 1

Related Questions