I am sure it should be just one line but I am not able to figure out the best to do this:
import numpy as np
import re
arr = np.array(["AB", "AC", "XAB", "XAC", "AD"])
I want to add "X" in the beginning based on a regex match of "^A".
I am sure it should be just one line but I am not able to figure out the best to do this:
import numpy as np
import re
arr = np.array(["AB", "AC", "XAB", "XAC", "AD"])
I want to add "X" in the beginning based on a regex match of "^A".
What about this:
print(np.array(list(map(lambda v: re.sub(r'^A','XA', v) ,arr))))
% outputs: ['XAB' 'XAC' 'XAB' 'XAC' 'XAD']
You can use the sub
function in re
module to substitute strings as
>>> import re
>>> str="ABC"
>>> re.sub('^(?=A)','X', str)
'XABC'
^(?=A)
is lookahead assertion which matches start postition in anystring that begins with 'A'