Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python's re.sub take an array as the input parameter?

According to http://www.php2python.com/wiki/function.preg-replace-callback/ re.sub is the python equivlant of PHP's preg_replace_callback, but the php version takes an array for the strings to be matched, so you can pass multiple strings, but the re.sub appears to take only a single string.

Is that right or is it my weak knowledge of python?

like image 588
vfclists Avatar asked Jan 23 '26 05:01

vfclists


2 Answers

If you want to do it on an array, you can use a list comprehension, e.g.

>>> array_of_strings = ["3a1", "1b2", "1c", "d"]
>>> [re.sub("[a-zA-Z]", "", elem) for elem in array_of_strings]
["31", "12", "1", ""]

though if you're using a complicated expression, you should probably use re.compile on the pattern first

like image 194
Jeff Tratner Avatar answered Jan 24 '26 19:01

Jeff Tratner


It only takes a single string http://docs.python.org/library/re.html#re.sub

like image 33
Matti Lyra Avatar answered Jan 24 '26 19:01

Matti Lyra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!