-2

I have the following string in Python.

"My number is 5"

How can I check to see if a string contains a number and subsequently extract it, thus giving me the string "5"?

Edit: By using the re module, I'm now getting the result [u,'5']. How can I get the number 5 out of this result?

Ben
  • 1,299
  • 3
  • 17
  • 37

1 Answers1

2

you need to use regex:

import re
my_num = re.findall("\d+","my number is 5")

\d+ match 1 or more occurence of [0-9]

demo to extract the number from 0-20:

>>> a ="my string may 0-20, but how to remove number like 30,22 etc"
>>> my_num = re.findall('\d+',a)
>>> [int(x) for x in my_num if int(x)<=20]
[0, 20]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72