简体   繁体   中英

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?

If you want to do it on an array, you can use a list comprehension, eg

>>> 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

Late to the party I know, but if this was a requirement for a many step process you wanted to encapsulate into a function, then you could process through numpy vectorize:

def EliminateAlpha(elem):
    return re.sub("[a-zA-Z]", "", elem)

ElimAlphaArray = np.vectorize(ElimateAlpha)

array_of_strings = ["3a1", "1b2", "1c", "d"]
print(ElimAlphaArray(array_of_strings))

['31' '12' '1' '']

Of course, you can use the re.sub function directly into vectorize:

ElimAlphaArr = np.vectorize(re.sub)
print(ElimAlphaArr("[a-zA-Z]", "", array_of_strings))

['31' '12' '1' '']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM