Python 字符串轉整數,整數轉字符串

在本教程中,我們將學習如何在Python中將字串轉換為整數,以及將整數轉換為字串。在我們之前的教程中,我們了解了Python List append函數。

Python String to Int

如果您閱讀我們之前的教程,您可能會注意到我們曾在某個時候使用了這種轉換。實際上,在許多情況下這是必要的。例如,您正在從文件中讀取一些數據,那麼它將以字串格式存在,您將不得不將字串轉換為整數。現在,我們將直接轉向代碼。如果您想將以字串表示的數字轉換為整數,您必須使用int()函數來執行此操作。請參見以下示例:

num = '123'  # string data

# 印出型別

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

# 使用 int() 轉換

num = int(num)

# 印出型別 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 :', num)

# 假设 '123' 是十进制,将其转换为十进制

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

# 假设 '123' 是八进制,将其转换为十进制

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

# 假设 '123' 是六进制,将其转换为十进制

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

以下代码的输出将是

Python Convert String To Int With Base

将字符串转换为整数时的 ValueError

當從字符串轉換為整數時,可能會出現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

# 轉換期間將變量視為十進制值
print('The value is :', int(num))

# 轉換期間將變量視為十六進制值
print('Actual value is :', int(num, base=16))

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

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

# 轉換期間將變量視為十六進制值
print('Actual value of \'1e\' is :', int(num, base=16))

# 轉換期間將變量視為十進制值
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 官方文檔

Source:
https://www.digitalocean.com/community/tutorials/python-string-to-int-int-to-string