So, I have a string "AB256+74POL". I want to extract the numbers only into a list say num = [256,74]. How to do this in python? I have tried string.split('+') and followed by iterating over the two parts and adding the characters which satisfy isdigit(). But is there an easier way to that?
Asked
Active
Viewed 243 times
2 Answers
0
"".join([c if c.isdigit() else " " for c in mystring]).split()
Explanation
Strings are iterable in python. So we iterate on each character in the string, and replace non digits with spaces, then split the result to get all sequences of digits in a list.

Valentin B.
- 602
- 6
- 18
-
No problem, however it is a bit "hacky", the "proper" way is what Sanil did in his answer i.e. using regular expressions. If you don't want to learn about regex or import `re` my solution should work fine. – Valentin B. Oct 10 '19 at 09:41