Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python if user input contains string

Very basic question. We have the code:

a = input("how old are you")

if a == string:
    do this

if a == integer (a != string):  
    do that

Obviously it doesn't work that way. But what is the easiest way to do this. Thanks for any answers in advance.

We could also say:

if string in a:
    do this
like image 878
Greg Peckory Avatar asked Jul 03 '13 16:07

Greg Peckory


2 Answers

You can use str.isdigit and str.isalpha:

if a.isalpha():
   #do something
elif a.isdigit():
   #do something

help on str.isdigit:

>>> print str.isdigit.__doc__
S.isdigit() -> bool

Return True if all characters in S are digits
and there is at least one character in S, False otherwise.

help on str.isalpha:

>>> print str.isalpha.__doc__
S.isalpha() -> bool

Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
like image 197
Ashwini Chaudhary Avatar answered Oct 07 '22 20:10

Ashwini Chaudhary


You can use a.isalpha(), a.isdigit(), a.isalnum() to check if a is composed of letters, numbers, or a combination of numbers and letters, respectively.

if a.isalpha(): # a is made up of only letters
    do this

if a.isdigit(): # a is made up of only numbers
    do this

if a.isalnum(): # a is made up numbers and letters
    do this

The Python docs will tell you in more detail the methods you can call on strings.

like image 2
jh314 Avatar answered Oct 07 '22 19:10

jh314