boef
boef

Reputation: 43

extract a substring from an array of strings in python

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

Upvotes: 4

Views: 32317

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601529

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

out = [x[1:3] for x in aa]

Upvotes: 17

Related Questions