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

新手上路,请多包涵

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

 a = input("how old are you")

if a == string:
    do this

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

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

我们也可以说:

 if string in a:
    do this

原文由 Greg Peckory 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 669
2 个回答

您可以使用 str.isdigitstr.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.

原文由 Ashwini Chaudhary 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 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 文档 将更详细地告诉您可以对字符串调用的方法。

原文由 jh314 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏