이원석
이원석

Reputation: 87

finding substring within a list in Python

I have a list like:

a = ['aaa/aa/aa/a001', 'aaa/aa/aa/a002', 'aaa/aa/aa/a003']

I want to retrieve the number part. How can I do that?

Upvotes: 2

Views: 83

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Using a list comprehension with re.sub:

a = ['aaa/aa/aa/a001','aaa/aa/aa/a002','aaa/aa/aa/a003']
out = [re.sub(r'^.*?(\d+)$', r'\1', x) for x in a]
print(out)

This prints:

['001', '002', '003']

The strategy here is to match and capture the digits at the end of each string in the list. Note that this approach is robust even if digits might also appear earlier in the string.

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71560

You could try regex:

import re
a = ['aaa/aa/aa/a001','aaa/aa/aa/a002','aaa/aa/aa/a003']
print([re.sub('[^\d+]', '', i) for i in a])

Output:

['001', '002', '003']

Or you could try using str.join:

print([''.join(x for x in i if x.isdigit()) for i in a])

Output:

['001', '002', '003']

Upvotes: 2

Synthaze
Synthaze

Reputation: 6080

import re

a = ['aaa/aa/aa/a001','aaa/aa/aa/a002','aaa/aa/aa/a003']

for elem in a:
    print (re.sub(r"[^0-9]","",elem))

Output:

001
002
003

Or, with list comprehension:

numbers = [re.sub(r"[^0-9]","",x) for x in a]

print (numbers)

Output:

['001', '002', '003']

Upvotes: 2

Related Questions