4

Is there a way how to extract an array (or list) of substrings (all characters from position 1 to position 2) from all elements of a string array (or a list of strings) without making a loop?

For example, I have: aa=['ab1cd','ab2ef'] , and I want my output to be: out=['b1','b2']

For a single string variable I would do out=aa[1:3], but I can't figure how to do it for a list or array (without a loop).

1 Answer 1

17

You will definitely need some kind of loop. A list comprehension is the easiest way:

out = [x[1:3] for x in aa]
Sign up to request clarification or add additional context in comments.

2 Comments

An alternative is map(lambda x: x[1:3], aa)
Thanks, you spared me a lot of time trying to figure it out! I usually work with IDL, and there most functions (including most string functions) can take an array as an argument. I assumed it is the same in Python, and I assumed wrong. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.