1

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" ]
1
  • So you want to get the first Y in uppercase? Commented Oct 8, 2019 at 19:22

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

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.