4

I would like to extract all the numbers contained in a string. I can't use regex, is there any other way?

Example:

minput = "BLP45PP32AMPY"

Result:

4532
  • 1
    I'm curious why you can't use regex. The `re` module is built in. – Mark Ransom Aug 03 '21 at 21:27
  • I'm writing a program on a website that can't import other libraries. (I think it's probably a compiler problem) I can only use basic commands. – BrilliantPy Aug 03 '21 at 22:06
  • 1
    Not sure what you mean by "other libraries". If it was something you had to install separately I'd understand, but the `re` module comes as part of Python. `import re` should work just as well as `import sys`. – Mark Ransom Aug 03 '21 at 23:51
  • Oh! It is available. I previously tried to import pandas/numpy and ran into a problem. So I avoid all imports. Many thanks. – BrilliantPy Aug 04 '21 at 04:38

2 Answers2

6

You can use str.isnumeric:

minput = "BLP45PP32AMPY"

number = int("".join(ch for ch in minput if ch.isnumeric()))
print(number)

Prints:

4532
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2
final_integer = int("".join([ i for i in minput if i.isdigit()]))
Jayakrishnan
  • 563
  • 5
  • 13
  • Interesting that there appears to be two string functions that do exactly the same thing. Kind of breaks the rule from [PEP 20 -- The Zen of Python](https://www.python.org/dev/peps/pep-0020/) - "There should be one-- and preferably only one --obvious way to do it." – Mark Ransom Aug 03 '21 at 21:32
  • 1
    They aren't exactly the same - see [here](https://stackoverflow.com/questions/44891070/whats-the-difference-between-str-isdigit-isnumeric-and-isdecimal-in-python) – sj95126 Aug 03 '21 at 22:06
  • Thanks @sj95126, that was fascinating. I still say it breaks the Zen of Python though. – Mark Ransom Aug 03 '21 at 23:47