且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-15 10:59:52

在使用 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.