Reputation: 2500
I have string that are always of the format track-a-b
where a
and b
are integers.
For example:
track-12-29
track-1-210
track-56-1
How do I extract a
and b
from such strings in python?
Upvotes: 1
Views: 64
Reputation: 70722
If it's just a single string, I would approach this using split:
>>> s = 'track-12-29'
>>> s.split('-')[1:]
['12', '29']
If it is a multi-line string, I would use the same approach ...
>>> s = 'track-12-29\ntrack-1-210\ntrack-56-1'
>>> results = [x.split('-')[1:] for x in s.splitlines()]
[['12', '29'], ['1', '210'], ['56', '1']]
Upvotes: 4
Reputation: 49320
You'll want to use re.findall()
with capturing groups:
results = [re.findall(r'track-(\d+)-(\d+)', datum) for datum in data]
Upvotes: 2