python 如果用户输入包含字符串 [英] python if user input contains string

查看:29
本文介绍了python 如果用户输入包含字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

a = input("你多大了")如果一个 == 字符串:做这个如果 a == 整数(a != 字符串):去做

显然它不会那样工作.但最简单的方法是什么.感谢您提前回答.

我们也可以说:

if 字符串在一个:做这个

解决方案

你可以使用str.isdigitstr.isalpha:

if a.isalpha():#做一点事elif a.isdigit():#做一点事

str.isdigit 的帮助:

<预><代码>>>>打印 str.isdigit.__doc__S.isdigit() ->布尔值如果 S 中的所有字符都是数字,则返回 TrueS 中至少有一个字符,否则为 False.

str.isalpha 的帮助:

<预><代码>>>>打印 str.isalpha.__doc__S.isalpha() ->布尔值如果 S 中的所有字符都是字母,则返回 TrueS 中至少有一个字符,否则为 False.

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

解决方案

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.

这篇关于python 如果用户输入包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆