3

I have strings like 6M1D14M. I would like to extract all the numbers from this string. Something like:

[6, 1, 14]

How do I do that? The length of the string can be arbitrary. Numbers that are present in between might also be of any length.

I have tried this approach but unable to split the string the way I need.

Community
  • 1
  • 1
Swetabh
  • 1,665
  • 2
  • 16
  • 21
  • 1
    Ok, This is what you want. But what you tried for it? SO is not for "Do this for me" – Moinuddin Quadri Nov 23 '16 at 17:53
  • You are right. I was trying this approach: http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string But unable to split the string the way I need. – Swetabh Nov 23 '16 at 17:57
  • You should mention with the question what you tried along withe the code. We like questions which shows efforts from the user. Then we can work on fixing your code together. Even you will get to know the better approach to do it – Moinuddin Quadri Nov 23 '16 at 18:00
  • Appreciate the advise. I believe the question is not a duplicate because the other question assumes spaces. How to adapt the code might be obvious to some people but sadly isn't to me. – Swetabh Nov 23 '16 at 18:09
  • It is duplicate. Because it doesn't matter whether you are having space, a character or something in latin as the part of your string. All you want is to extract the numbers from the string. There are many approaches to do that which are already mentioned as an answer to the question related here – Moinuddin Quadri Nov 23 '16 at 18:15
  • @MoinuddinQuadri I do not think it is duplicate, the question you mentioned having marked answer which did not work for me. However, the solution here worked. – Khalil Al Hooti Apr 23 '18 at 00:33

1 Answers1

10

Use findAll with regex \d+

>>> import re
>>> re.findall(r"\d+", "6M1D14M")
['6', '1', '14']

For converting into integer list just iterate and parse them.

>>> import re
>>> [int(num) for num in re.findall(r"\d+", "6M1D14M")]
[6, 1, 14]
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188