4

Does anyone know how to use re.sub in Python with list comprehensions.

Im using the following,

>>> a = ["N","!","1","abc"]
>>> [(re.sub(r'(h|N|!|N|1)', r"'\033[91m'\g<1>'\033[0m'", 'x')) for x in a]
['x', 'x', 'x', 'x']

As you can see Im only getting x returned as the list elements.

Thanks,

2
  • 1
    I see you're doing for x in a, but you never actually use the x variable. Is that intentional? Commented Aug 8, 2014 at 13:44
  • 1
    Unquote 'x' and it will work. Commented Aug 8, 2014 at 13:45

1 Answer 1

5

As Kevin commented, you didn't used x, but used the string literal 'x':

>>> [(re.sub(r'(h|N|!|N|1)', r"'\033[91m'\g<1>'\033[0m'", x)) for x in a]
["'\x1b[91m'N'\x1b[0m'", "'\x1b[91m'!'\x1b[0m'", "'\x1b[91m'1'\x1b[0m'", 'abc']

UPDATE

The regular expression can be expressed using character class ([....]) if the components are all single-character strings.

>>> [(re.sub(r'([hN!1])', r"'\033[91m'\g<1>'\033[0m'", x)) for x in a]
["'\x1b[91m'N'\x1b[0m'", "'\x1b[91m'!'\x1b[0m'", "'\x1b[91m'1'\x1b[0m'", 'abc']
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.