Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract a substring from an array of strings in python

Tags:

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

like image 772
boef Avatar asked Dec 03 '22 08:12

boef


1 Answers

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

out = [x[1:3] for x in aa]
like image 98
Sven Marnach Avatar answered Jan 30 '23 15:01

Sven Marnach