-1

I am trying to check if in a string(eg "Hello my name is 3") if there is a number. In my example the code I want to write would identify the number 3.

I have tried the code bellow. I know the "int(range(1,10)): " part is not going to work at all but I put it there to show what im trying to achieve if that makes sense.

for x in text:
    if x != " " or x != int(range(1,10)):
        print(x)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 3
    Possible duplicate of [Check if a string contains a number](https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number) – Georgy Oct 07 '19 at 09:04

4 Answers4

0

To test if string contains a number:

>>> def hasNumbers(inputString):
...     return any(char.isdigit() for char in inputString)

>>> hasNumbers("Hello my name is 3")
True
>>> hasNumbers("Hello my name is p")
False

To extract number:

>>> int(filter(str.isdigit, inputString))
3
Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20
0

You've got the right idea, you just need another for loop after the first.

for i in range(1,10): #this will only check 1-9
    if i != int(x):
        print(x)

Alternatively, you could use regular expressions, which would be faster with a larger range of numbers;

import re
if not re.match("[0-9]",x):
    print(x)

This checks for a digit 0-9 in x, and prints if it's not there.

Corsaka
  • 364
  • 3
  • 15
0

If you want to just test that your string has a proper decimal, try this

test='Hello my name is 3'
if any((x.isdecimal() for x in test.split())):
   # Yes

Note: This won' work for example, Hello my name is3

If you want to check digit-by-digit, then just remove the split.

any((x.isdecimal() for x in test))
Sam Daniel
  • 1,800
  • 12
  • 22
0

Solution

Use regular expression library: regex

import re
s = "Hello my name is 3"

re.findall("\d*", s)

Output

3
CypherX
  • 7,019
  • 3
  • 25
  • 37