-2

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!

Tagc
  • 8,736
  • 7
  • 61
  • 114

2 Answers2

8

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]
2ps
  • 15,099
  • 2
  • 27
  • 47
  • Right you are. Updated with a list expansion and `isdigit`. – 2ps Jan 07 '17 at 20:09
  • and that's a very good regex answer. you're lucky since it only deals with positive numbers, else it's very difficult to make it fit in a listcomp. Maybe you could explain that it works because regexes are greedy by default. – Jean-François Fabre Jan 07 '17 at 20:10
  • Agreed: but I figured it would be best to just answer the OP before dealing with additional complexity. My thanks for the clarification on the OP’s question earlier. – 2ps Jan 07 '17 at 20:13
  • you're welcome. You already did the hard part. – Jean-François Fabre Jan 07 '17 at 20:16
4

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126