鱼C论坛

 找回密码
 立即注册
查看: 2147|回复: 3

[已解决]咨询下python3的input

[复制链接]
发表于 2017-12-24 16:24:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
问大家一个问题,我需要判断输入的是数字类型的还是字符串类型的

py3的input函数返回的值都是str


以下是我的代码
  1. a =  input()
  2. if type(a) == int:
  3.     print ("你输入的是数字类型")
  4. else:
  5.     print ('非')
复制代码


返回都是str  ,请问应该怎么解决呢~~


最佳答案
2017-12-24 17:10:54
本帖最后由 payton24 于 2017-12-24 17:12 编辑

可使用str的方法isdigit来解决,具体如下:
  1. a =  input('请输入')
  2. if a.isdigit():
  3.     print ("你输入的是数字类型")
  4. else:
  5.     print ('非')
复制代码


附上isdigit的用法说明,可以在shell上使用help(str.isdigit) 来查询:
  1. >>> help(str.isdigit)
  2. Help on method_descriptor:

  3. isdigit(...)
  4.     S.isdigit() -> bool
  5.    
  6.     Return True if all characters in S are digits
  7.     and there is at least one character in S, False otherwise.
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-12-24 17:10:54 | 显示全部楼层    本楼为最佳答案   
本帖最后由 payton24 于 2017-12-24 17:12 编辑

可使用str的方法isdigit来解决,具体如下:
  1. a =  input('请输入')
  2. if a.isdigit():
  3.     print ("你输入的是数字类型")
  4. else:
  5.     print ('非')
复制代码


附上isdigit的用法说明,可以在shell上使用help(str.isdigit) 来查询:
  1. >>> help(str.isdigit)
  2. Help on method_descriptor:

  3. isdigit(...)
  4.     S.isdigit() -> bool
  5.    
  6.     Return True if all characters in S are digits
  7.     and there is at least one character in S, False otherwise.
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-12-24 17:49:18 From FishC Mobile | 显示全部楼层
a.isdigit()判断它是不是纯数字
int(a) 将它转换为整形
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-12-24 19:57:29 | 显示全部楼层
payton24 发表于 2017-12-24 17:10
可使用str的方法isdigit来解决,具体如下:

感谢 明白了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-5 02:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表