在本教程中,我们将学习如何在python中将python字符串转换为int,并将int转换为String。在之前的教程中,我们了解到Python列表附加功能。
Python字符串到Int
如果您阅读了我们以前的教程,您可能会注意到我们在某些时候使用了这种转换。实际上,这在很多情况下是必要的。例如,您正在从一个文件中读取一些数据,然后它将是字符串格式,并且您必须将字符串转换为int。
现在,我们将直接进入代码。如果要将字符串中表示的数字转换为int,则必须使用int()
function to do so. See the following example:
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字符串到Int
将字符串从不同的基转换为int
如果要转换为int的字符串属于以10为底的不同基数,则可以指定转换的基数。但请记住,输出的整数总是以10为基数。你需要记住的另一件事是给定的基数必须在2到36之间。请参阅下面的示例,以了解使用基参数将字符串转换为int。
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))
以下代码的输出将是
Python将字符串转换为带基的Int
将字符串转换为int时出错
从字符串转换为int时,您可能会得到ValueError
例外. 如果要转换的字符串不代表任何数字,则会发生此异常。
假设要将十六进制数转换为整数。但你们并没有通过辩论基数=16在整数()功能。它会引起ValueError
exception if there is any digit that does not belong to the decimal number system. The following example will illustrate this exception while converting a string to int.
"""
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字符串到Int值错误
Python int到String
将int转换成字符串不需要任何努力或检查。你只要用str()
function to do the conversion. See the following example.
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到String的转换
这就是Python将字符串转换为int和int到字符串转换的全部内容。
参考文献:Python官方文档