【问题标题】:Convert input str to int in python [duplicate]在python中将输入字符串转换为int [重复]
【发布时间】:2019-09-17 01:05:04
【问题描述】:

我得到错误代码:

TypeError: '>' 在 'str' 和 'int' 的实例之间不支持 它的当前状态。

问题是我不知道如何将用户输入期望从字符串格式转换为整数。

number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")

我已经查找了如何执行此操作,但找不到我要查找的内容,因为我不确定如何正确表达我的问题。

我尝试将“int”放在numberinput 之后,但它不起作用。不知道把它放在哪里让它工作。

【问题讨论】:

  • 当我输入 input(int)etc... 它打印 我不知道那是什么意思。
  • 只需将int 放在input 之前。例如。 number=int(input("question"))
  • 这个方法也在shell中返回
  • 啊,没关系,我忘了在输入部分之后删除“int”。谢谢!

标签: python math structure typeerror conventions


【解决方案1】:

默认情况下,输入类型为string。要将其转换为integer,只需将int 放在input 之前。例如。

number = int(input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: "))
print(type(number))

输出示例:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 30
<class 'int'>   # it shows that the input type is integer

替代

# any input is string
number = input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: ")   
try:                      # if possible, try to convert the input into integer
    number = int(number)
except:                   # if the input couldn't be converted into integer, then do nothing
    pass
print(type(number))       # see the input type after processing

输出示例:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 25    # the input is a number 25
<class 'int'>   # 25 is possible to convert into integer. So, the type is integer

Please guess what number I'm thinking of. HINT: it's between 1 and 30: AAA   # the input is a number AAA
<class 'str'>   # AAA is impossible to convert into integer. So, the type remains string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多