[英]python if user input contains string
非常基本的問題。 我們有以下代碼:
a = input("how old are you")
if a == string:
do this
if a == integer (a != string):
do that
顯然,這種方式行不通。 但是最簡單的方法是這樣做。 感謝您提前提出任何答案。
我們還可以說:
if string in a:
do this
您可以使用str.isdigit
和str.isalpha
:
if a.isalpha():
#do something
elif a.isdigit():
#do something
幫助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.
幫助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.
您可以使用a.isalpha(),a.isdigit(),a.isalnum()來檢查a是否分別由字母,數字或數字和字母的組合組成。
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
Python 文檔將更詳細地告訴您可以調用字符串的方法。
看到您在游覽示例中使用了input(),您應該知道輸入始終會為您提供一個字符串。 您需要將其強制轉換為正確的類型,例如EG:Int或Float。
def isint(input):
return input.isdigit()
def isfloat(input):
try:
return float(input) != None;
except ValueError:
return False;
def isstr(input):
if not isint(input) and not isfloat(input):
return True
return False
print isint("3.14")
print isfloat("3.14")
print isstr("3.14")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.