Skip to content
Advertisement

Extract digits from string by condition

I want to extract digits from a short string, base on a condition that the digits is in front of a character (S flag).

example and result:

> string = '10M26S'
> 26

> string = '18S8M10S'
> [18,10] OR 28

> string = '7S29M'
> 7

I can split the string to a list to get the individual element,

result = [''.join(g) for _, g in groupby('18S8M10S', str.isalpha)]
> ['18', 'S', '8', 'M', '10', 'S'] 

but how could I just get the 18 and 10?

Advertisement

Answer

Use re.findall with the regex r'(d+)S'. This matches all digits before a capital S.

>>> string = '10M26S'
>>> re.findall(r'(d+)S',string)
['26']
>>> string = '18S8M10S'
>>> re.findall(r'(d+)S',string)
['18', '10']
>>> string = '7S29M'
>>> re.findall(r'(d+)S',string)
['7']

To get integer output, you can convert them in a list comp or use map

>>> list(map(int,['18', '10']))
[18, 10]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement