I want to extract numbers in a string into a list but also include the other letters.
For example:
a='a815e8ef951'
Should result in the output:
['a',815,'e',8,'f',951]
Thanks!
I want to extract numbers in a string into a list but also include the other letters.
For example:
a='a815e8ef951'
Should result in the output:
['a',815,'e',8,'f',951]
Thanks!
You can use a regular expression and re
for this:
import re
matches = re.findall(r'(\d+|\D+)', 'a815e8ef951')
matches = [ int(x) if x.isdigit() else x for x in matches ]
# Output: ['a', 815, 'e', 8, 'ef', 951]
You main use itertools.groupby
along with list comprehension expression as:
>>> from itertools import groupby, chain
>>> a='a815e8ef951'
>>> [''.join(s) for _, s in groupby(a, str.isalpha)]
['a', '815', 'e', '8', 'ef', '951']
If you also want to convert the integer string to int
, you have to modify the expression as:
>>> [''.join(s) if i else int(''.join(s)) for i, s in groupby(a, str.isalpha)]
['a', 815, 'e', 8, 'ef', 951]
In order to make the last expression little cleaner, you make move the if
part to some function as:
def tranform_string(to_int, my_list):
my_string = ''.join(my_list)
return int(my_string) if to_int else my_string
new_list = [tranform_string(i, s) for i, s in groupby(a, str.isdigit)]
# using `isdigit()` here ^
where new_list
will hold the required content.