python如果用户输入包含字符串

Gre*_*ory 5 python string if-statement input python-3.x

非常基本的问题.我们有代码:

a = input("how old are you")

if a == string:
    do this

if a == integer (a != string):  
    do that
Run Code Online (Sandbox Code Playgroud)

显然它不会那样工作.但是最简单的方法是什么呢.感谢您提前得到任何答案.

我们也可以说:

if string in a:
    do this
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 15

你可以使用str.isdigitstr.isalpha:

if a.isalpha():
   #do something
elif a.isdigit():
   #do something
Run Code Online (Sandbox Code Playgroud)

帮助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.
Run Code Online (Sandbox Code Playgroud)

帮助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.
Run Code Online (Sandbox Code Playgroud)