Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace in List Comprehension in Python

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,

like image 217
felix001 Avatar asked Sep 03 '25 03:09

felix001


1 Answers

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']
like image 51
falsetru Avatar answered Sep 06 '25 13:09

falsetru