在Python中将输入结果/字符串转换为整数

在Python中将输入结果/字符串转换为整数,python,string,integer,Python,String,Integer,我在运行此代码时遇到问题。当我试着运行它时,它说它不会工作,因为年龄是一个字符串。如何将字符串转换为整数?我也尝试过做18整数(年龄),但那也不行 age = input ("How old are you? (): ") if int(age) > 18 : print("You're old enough to drink") else: print("You're not ol

我在运行此代码时遇到问题。当我试着运行它时,它说它不会工作,因为年龄是一个字符串。如何将字符串转换为整数?我也尝试过做18整数(年龄),但那也不行

    age = input ("How old are you? (): ")
    if int(age) > 18 :
        print("You're old enough to drink") 
    else:
        print("You're not old enough to drink. Wait", + 18 - age, "more years")
请注意,
input(“你多大了?”():”
int(input(“你多大了?”():”)

age=int(输入(“你多大了?():”)
如果int(年龄)>18岁:
打印(“你已经可以喝酒了”)
其他:
打印(“你还没到喝酒的年龄。再等{}年”。格式(18岁))
您可以添加

像这样:

age = input("How old are you? (): "))
try:
    age = int(age)
    if age > 18 :
        print("You're old enough to drink.") 
    else:
        print(f"You're not old enough to drink. Wait {18-age} more years.")
except ValueError:
    print("Not a valid age. Please enter again")
顺便说一下,您可以使用
f'
字符串作为字符串格式

或使用
.format

print("You're not old enough to drink. Wait {0} more years.".format(18-age))

你能和我们分享一下这个代码产生的输出和你期望它产生的输出吗?你在哪里做
if int(age)>18
,用你自己的话来说:a)
int(age)
部分是什么意思?b) 您希望这会修改年龄吗?为什么?为什么不?“我也试过做18-int(年龄),但那也不行。”你说“不行”是什么意思?你到底是如何“尝试”这一点的;当你尝试时发生了什么;这和应该发生的情况有什么不同?可能是你输入的字符串像“19.0”…如果str有str格式的浮点,你不能直接将str转换成int。。。。您可以使用float进行此操作。。。浮动(年龄)
print("You're not old enough to drink. Wait {0} more years.".format(18-age))