在python中将输入str转换为int [英] Convert input str to int in python

查看:227
本文介绍了在python中将输入str转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到错误代码:

TypeError:>"在以下实例中的"str"和"int"实例之间不受支持其当前状态.

TypeError: '>' not supported between instances of 'str' and 'int' in its current state.

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

The problem is that I don't know how to convert user input expectations to integer from string format.

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

我一直在寻找方法,但是找不到我想要的东西,因为我不确定如何正确表达我的问题.

I've looked up how to do it but I couldn't find what I was looking for because I'm not sure how to word my question properly.

我尝试将" int "放在 number 之后和 input 之后,但是它不起作用.不确定将其放置在何处才能正常工作.

I've tried putting "int" after number and after input but it doesn't work. Not sure where to put it to get it to work.

推荐答案

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

By default, the input type is string. To convert it into integer, just put int before input. E.g.

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

这篇关于在python中将输入str转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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