3

I have such strings; '17.', '0,5', ',5', 'CO2-heidet', '1990ndatel', etc. I want to split them as follows: ['17', '.'], ['0', ',', '5'], [',', '5'], ['CO', '2', '-heidet'], ['1990', 'ndatel'], etc.

How can I do this efficiently in python?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
yusuf
  • 3,591
  • 8
  • 45
  • 86

2 Answers2

4

You may also use itertools.groupby() with key as str.isdigit to achieve this as:

>>> from itertools import groupby
>>> my_list = ['17.', '0,5', ',5', 'CO2-heidet', '1990ndatel']

>>> [[''.join(j) for i, j in groupby(l, str.isdigit)] for l in my_list]
[['17', '.'], ['0', ',', '5'], [',', '5'], ['CO', '2', '-heidet'], ['1990', 'ndatel']]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
3

Here's a way with re.split:

In [1]: import re

In [2]: def split_digits(s):
   ...:     return [g for g in re.split(r'(\d+)', s) if g]
   ...: 

In [3]: for s in ['17.', '0,5', ',5', 'CO2-heidet', '1990ndatel']:
   ...:     print(repr(s), 'becomes', split_digits(s))
   ...:     
'17.' becomes ['17', '.']
'0,5' becomes ['0', ',', '5']
',5' becomes [',', '5']
'CO2-heidet' becomes ['CO', '2', '-heidet']
'1990ndatel' becomes ['1990', 'ndatel']
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175