在 Python 中使用 try/except 将 String 转换为 Int [英] Converting String to Int using try/except in Python
问题描述
所以我对如何使用 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 将 String 转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!