在 Python 中使用 try/except 将字符串转换为 Int

2022-01-31 00:00:00 python python-3.x

问题描述

所以我很困惑如何使用 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.

相关文章