将Python字符串转换为Int,将Int转换为String
时间:2020-02-23 14:43:32 来源:igfitidea点击:
在本教程中,我们将学习如何在python中将python字符串转换为int以及将int转换为String。
将Python字符串转换为Int
如果您阅读了以前的教程,您可能会注意到有时我们使用了这种转换。
实际上,在许多情况下这是必要的。
例如,您正在从文件中读取某些数据,那么它将采用String格式,则必须将String转换为int。
现在,我们将直接进入代码。
如果要将字符串中表示的数字转换为int,则必须使用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'>
从不同的基础将String转换为int
如果要转换为int的字符串属于除10以外的其他数字基数,则可以指定转换的基数。
但是请记住,输出整数始终以10为底。
您需要记住的另一件事是,给定的底数必须在2到36之间。
请参见以下示例,以了解使用base参数将字符串转换为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))
将String转换为int时发生ValueError
从字符串转换为int时,可能会出现" ValueError"异常。
如果要转换的字符串不代表任何数字,则会发生此异常。
假设您要将十六进制数转换为整数。
但是您没有在int()函数中传递参数base = 16。
如果有任何数字不属于十进制系统,它将引发" ValueError"异常。
下面的示例将说明在将字符串转换为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转换为String
将int转换为字符串无需费力或者检查。
您只需要使用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'>

