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,
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With