如何在 Python 中將整數轉換為字串?


型別轉換有時在使用者希望根據需要將一種資料型別轉換為另一種資料型別時是必需的。

Python 內建函式 str() 用於將整數轉換為字串。除了此方法之外,我們還將討論其他幾種方法,以在 Python 中將整數轉換為字串。

使用 str()

這是在 Python 中將整數轉換為字串最常用的方法。str() 將整數變數作為引數並將其轉換為字串。

語法

str(integer variable)

示例

 即時演示

num=2
print("Datatype before conversion",type(num))
num=str(num)
print(num)
print("Datatype after conversion",type(num))

輸出

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

type() 函式給出作為引數傳遞的變數的資料型別。

在上面的程式碼中,轉換前,num 的資料型別是 int,轉換後,num 的資料型別是 str(即 Python 中的字串)。

使用 f-字串

語法

f ’{integer variable}’

示例

 即時演示

num=2
print("Datatype before conversion",type(num))
num=f'{num}'
print(num)
print("Datatype after conversion",type(num))

輸出

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

使用 “%s” 關鍵字

語法

“%s” % integer variable

示例

 即時演示

num=2
print("Datatype before conversion",type(num))
num="%s" %num
print(num)
print("Datatype after conversion",type(num))

輸出

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

使用 .format() 函式

語法

‘{}’.format(integer variable)

示例

 即時演示

num=2
print("Datatype before conversion",type(num))
num='{}'.format(num)
print(num)
print("Datatype after conversion",type(num))

輸出

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

這些是在 Python 中將整數轉換為字串的一些方法。在某些情況下,我們可能需要將整數轉換為字串,例如將保留在整數中的值附加到某個字串變數中。一個常見的場景是反轉整數。我們可以將其轉換為字串,然後反轉,這比實現反轉整數的數學邏輯更容易。

更新於: 2021年3月10日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.