2

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

2 Answers 2

2

What about this:

print(np.array(list(map(lambda v: re.sub(r'^A','XA', v) ,arr))))
% outputs: ['XAB' 'XAC' 'XAB' 'XAC' 'XAD']
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! :) I ended up using the regex pattern from @nu11p01n73R instead of "^A"
Using a list comprehension is shorter: np.array([re.sub('^A','XA',a) for a in arr]). Does arr need to be an array, or return one? This looks like a list of strings problem, not a numpy one.
Ohh I see. Yeah - it need not be a numpy array.
0

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'

2 Comments

Thanks. I combined your and Marcin's solution.
@KapilSharma glad to hear it worked :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.