Converting String to Int using try/except in Python(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中使用 try/except 将字符串转换为 Int


- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01