5

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
4
  • 1
    I'm curious why you can't use regex. The re module is built in. Commented Aug 3, 2021 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. Commented Aug 3, 2021 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. Commented Aug 3, 2021 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. Commented Aug 4, 2021 at 4:38

2 Answers 2

6

You can use str.isnumeric:

minput = "BLP45PP32AMPY"

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

Prints:

4532
Sign up to request clarification or add additional context in comments.

Comments

2
final_integer = int("".join([ i for i in minput if i.isdigit()]))

3 Comments

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 - "There should be one-- and preferably only one --obvious way to do it."
They aren't exactly the same - see here
Thanks @sj95126, that was fascinating. I still say it breaks the Zen of Python though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.