-3

I am a newbie in Python. I am making a program where I take a input from user and check if any number is inside in the string. I am checking it by taking it in a variable. Is it not correct to check via a VARIABLE?

user_string=input("Enter the Word:")
print (user_string)
for index in (0,9):
    number=str(index)           #Typecasting Int to String 
    if number in user_string:   #Check if Number exist in the string
    print ("yes")

output:

Enter the Word:helo2
helo2
HelloWorld
  • 81
  • 1
  • 12

2 Answers2

2

You can use the string method isdigit() on each character in a generator expression within any. This will short-circuit upon finding the first numeric character (if one is present)

>>> user_string = 'helo2'
>>> any(i.isdigit() for i in user_string)
True

>>> user_string = 'hello'
>>> any(i.isdigit() for i in user_string)
False
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

Look at your for-loop. You are looping over a tuple (0,9). So actually you are only testing for 0 and 9. Use range(10) instead.

More elegant, to get the numbers inside your string, you can use sets:

import string
print 'yes' if set(string.digits).intersection(user_string) else 'no'
Daniel
  • 42,087
  • 4
  • 55
  • 81