如何将字符串转换为 Python 中的浮点数

介紹

在本文中,我們將使用Python的float()函數將字符串轉換為浮點數。我們還將使用Python的str()函數將浮點數轉換為字符串。

在進行計算和連接之前,正確地轉換數據類型非常重要,以防止運行時錯誤。

先決條件

完成本教程需要:

本教程在Python 3.9.6中進行了測試。

使用float()函數

我們可以使用 float() 函數將字符串轉換為浮點數。這是一個內置函數,用於將對象轉換為浮點數。在內部,float() 函數調用指定對象的 __float__() 函數。

示例

讓我們看一個在Python中將字符串轉換為浮點數的示例:

input_1 = '10.5674'

input_1 = float(input_1)

print(type(input_1))
print('Float Value =', input_1)

輸出:

<class 'float'>
Float Value = 10.5674

字符串值 '10.5674' 已轉換為浮點數值 10.5674

為什麼我們需要將字符串轉換為浮點數?

如果我們通過終端獲取用戶輸入的浮點數值,或者從文件中讀取它們,那麼它們就是字符串對象。我們必須明確將它們轉換為浮點數,以便我們可以對它們執行必要的操作,如加法、乘法等。

input_1 = input('Please enter first floating point value:\n')
input_1 = float(input_1)

input_2 = input('Please enter second floating point value:\n')
input_2 = float(input_2)

print(f'Sum of {input_1} and {input_2} is {input_1+input_2}')

注意:如果您對使用 f 前綴的字符串格式化不熟悉,請閱讀 Python 中的 f-strings

讓我們運行這段代碼,並為 input_1input_2 提供浮點數值:

Please enter first floating point value:
10.234
Please enter second floating point value:
2.456
Sum of 10.234 and 2.456 is 12.69

結果總和10.2342.45612.69

理想情況下,我們應該使用try-except塊來捕捉用戶輸入的無效異常。

使用str()函數

我們還可以使用str()函數將浮點數轉換為字符串。這在我們想要連接浮點數值的情況下可能是必需的。

例子

讓我們看一個例子:

input_1 = 10.23
input_2 = 20.34
input_3 = 30.45

# 使用Python 3.6+的f-string,對於舊版本請改用format()
print(f'Concatenation of {input_1} and {input_2} is {str(input_1) + str(input_2)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{str(input_1)},{str(input_2)},{str(input_3)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{", ".join([str(input_1),str(input_2),str(input_3)])}')

運行這段代碼:

Concatenation of 10.23 and 20.34 is 10.2320.34
CSV from 10.23, 20.34 and 30.45:
10.23,20.34,30.45
CSV from 10.23, 20.34 and 30.45:
10.23, 20.34, 30.45

10.2320.34串聯起來會產生字符串'10.2320.34'。此代碼還生成兩個版本的逗號分隔值(CSV)。

如果我們在上述程序中不將浮點數轉換為字符串,join()函數將拋出異常。此外,我們將無法使用+運算符進行連接,因為它將添加浮點數。

結論

您可以從我們的GitHub存儲庫查看完整的Python腳本和更多Python示例。

參考資料:

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