深度阅读

in python how to convert string to int ?

作者
作者
2023年08月22日
更新时间
7.28 分钟
阅读时间
0
阅读量

To convert a string to an integer in Python, you can use the built-in int() function.

Here is an example:

my_string = "123"
my_int = int(my_string)
print(my_int)

This will output 123, which is the integer representation of the string “123”.

If the string contains non-numeric characters or is empty, the int() function will raise a ValueError exception. To avoid this, you can use a try-except block to handle the exception.

Here is an example with error handling:

my_string = "abc"
try:
    my_int = int(my_string)
except ValueError:
    print("Could not convert to int")
else:
    print(my_int)

This will output “Could not convert to int”, since “abc” cannot be converted to an integer.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。