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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17453626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:15:20  来源:igfitidea点击:

python if user input contains string

pythonstringif-statementinputpython-3.x

提问by Greg Peckory

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

采纳答案by Ashwini Chaudhary

You can use str.isdigitand str.isalpha:

您可以使用str.isdigitstr.isalpha

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

help on str.isdigit:

帮助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:

帮助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.

回答by jh314

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.

您可以分别使用 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

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

Python文档将更详细地告诉您可以对字符串调用的方法。

回答by JHolta

Seen that you use input() in tour example you should know that input always give you a string. And you need to cast it to the correct type, EG: Int, or Float.

看到您在游览示例中使用 input() ,您应该知道 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")