2

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?

1
  • Hey, did the answers help? Commented Jan 12, 2021 at 16:33

3 Answers 3

2
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']
Sign up to request clarification or add additional context in comments.

Comments

2

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']

Comments

2

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.

5 Comments

If I have a = ['aaa/aa/aa/Lv2a001','aaa/aa/aa/Lv2a002','aaa/aa/aa/Lv2a003'], Is it possible to get ['001', '002', '003'] ?
@이원석 My answer also should work for this input. Check the demo.
Thanks a lot. Finally, I have a one further question. Then if i want to extract the earlier number from 'aaa/aa/aa/L2a001.he5' what should I change ?
@이원석 Use the regex pattern ^.*?(\d+)\D+\d+$ and then also access the first capture group \1 as the replacement.
I'd drop all the ancestor nodes, via value.split("/")[-1] first, before using your regex. That avoids numerical patterns higher up impacting what seems to concern only the leaves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.