将Python字符串转换为整数,整数转换为字符串

在这个教程中,我们将学习如何在Python中将字符串转换为整数以及将整数转换为字符串。在之前的教程中,我们学习了关于Python列表append函数的内容。

将Python字符串转换为整数

如果您阅读了我们之前的教程,您可能会注意到有时我们使用了这种转换。实际上,在许多情况下,这是必要的。例如,您正在从文件中读取一些数据,那么它将是一个字符串格式,您将需要将字符串转换为整数。现在,我们直接进入代码部分。如果您想将字符串表示的数字转换为整数,您必须使用int()函数来进行转换。请参考以下示例。

num = '123'  # string data

# print the type

print('Type of num is :', type(num))

# convert using int()

num = int(num)

# print the type again

print('Now, type of num is :', type(num))

以下代码的输出结果将是什么?

Type of num is : <class 'str'>
Now, type of num is : <class 'int'>
Python String To Int

将字符串从不同进制转换为整数

如果你想要转换的字符串属于除了十进制以外的其他进制,你可以指定转换的进制。但请记住,输出的整数始终是十进制的。另外,你需要记住给定的进制必须在2到36之间。请参考以下示例以理解使用进制参数进行字符串转换为整数的过程。

num = '123'
# print the original string
print('The original string :', num)

# considering '123' be in base 10, convert it to base 10

print('Base 10 to base 10:', int(num))

# considering '123' be in base 8, convert it to base 10

print('Base 8 to base 10 :', int(num, base=8))

# considering '123' be in base 6, convert it to base 10

print('Base 6 to base 10 :', int(num, base=6))
Example of Python String to Int conversion
Python Convert String To Int Base

将字符串转换为整数时出现数值错误。

在将字符串转换为整数时,您可能会遇到ValueError异常。如果要转换的字符串不代表任何数字,就会出现这种异常。假设您想将一个十六进制数转换为整数。但是在int()函数中没有传递base=16的参数。如果有任何不属于十进制数制的数字,它将引发一个ValueError异常。下面的示例将说明在将字符串转换为整数时出现此异常。

"""
    Scenario 1: The interpreter will not raise any exception but you get wrong data
"""
num = '12'  # this is a hexadecimal value

# the variable is considered as decimal value during conversion
print('The value is :', int(num))

# the variable is considered as hexadecimal value during conversion
print('Actual value is :', int(num, base=16))

"""
    Scenario 2: The interpreter will raise ValueError exception
"""

num = '1e'  # this is a hexadecimal value

# the variable is considered as hexadecimal value during conversion
print('Actual value of \'1e\' is :', int(num, base=16))

# the variable is considered as decimal value during conversion
print('The value is :', int(num))  # this will raise exception

以上代码的输出将会是:

The value is : 12
Actual value is : 18
Actual value of '1e' is : 30
Traceback (most recent call last):
  File "/home/imtiaz/Desktop/str2int_exception.py", line 22, in 
    print('The value is :', int(num))  # this will raise exception
ValueError: invalid literal for int() with base 10: '1e'
Python String To Int ValueError

将Python中的整数转换为字符串

将一个整数转换为字符串无需任何努力或检查。您只需使用str()函数进行转换。请参考以下示例。

hexadecimalValue = 0x1eff

print('Type of hexadecimalValue :', type(hexadecimalValue))

hexadecimalValue = str(hexadecimalValue)

print('Type of hexadecimalValue now :', type(hexadecimalValue))

下面代码的输出将是:

Type of hexadecimalValue : <class 'int'>
Type of hexadecimalValue now : <class 'str'>
Python Int To String Conversion

关于Python将字符串转换为整数和将整数转换为字符串的内容就是这些。参考资料:Python官方文档。

广告
将在 10 秒后关闭
bannerAds