在 Python 中使用 try/except 将字符串转换为 Int [英] Converting String to Int using try/except in Python

查看:32
本文介绍了在 Python 中使用 try/except 将字符串转换为 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我很困惑如何使用 try/except 函数将字符串转换为 int.有谁知道如何做到这一点的简单功能?我觉得我在字符串和整数上仍然有点朦胧.我非常有信心整数与数字有关.字符串...不是那么多.

So I'm pretty stumped on how to convert a string into an int using the try/except function. Does anyone know a simple function on how to do this? I feel like I'm still a little hazy on string and ints. I'm pretty confident that ints are related to numbers. Strings...not so much.

推荐答案

在使用 try/except 块时,具体说明您要捕获的异常非常重要.

It is important to be specific about what exception you're trying to catch when using a try/except block.

string = "abcd"
try:
    string_int = int(string)
    print(string_int)
except ValueError:
    # Handle the exception
    print('Please enter an integer')

Try/Excepts 非常强大,因为如果某事可能以多种不同的方式失败,您可以指定您希望程序在每种失败情况下如何反应.

Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.

这篇关于在 Python 中使用 try/except 将字符串转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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