如何在Python中將整數轉換為字符串
Python有幾種內置數據類型。 有時,在編寫Python代碼時,您可能需要將一種數據類型轉換為另一種數據類型。 例如,連接一個字符串和整數,首先,您需要將整數轉換為字符串。
本文介紹了如何將Python整數轉換為字符串。
蟒蛇 str()
功能編號
在Python中,我們可以使用內置函數將整數和其他數據類型轉換為字符串 str()
功能。
的 str()
函數返回給定對象的字符串版本。 它採取以下形式:
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
object
-要轉換為字符串的對象。
該函數接受三個參數,但是通常,當將整數轉換為字符串時,您只會傳遞一個參數(object
)的功能。
將Python整數轉換為字符串
要將整數23轉換為字符串版本,只需將數字傳遞到 str()
功能:
str(23)
type(days)
'23'
<class 'str'>
23周圍的引號表示數字不是整數,而是字符串類型的對象。 另外, type()
函數顯示該對象是一個字符串。
在Python中,字符串使用單('
),雙("
)或三引號("""
)。
連接字符串和整數
讓我們嘗試使用來連接字符串和整數 +
運算符並打印結果:
number = 6
lang = "Python"
quote = "There are " + number + " relational operators in " + lang + "."
print(quote)
Python會拋出一個 TypeError
異常錯誤,因為它無法連接字符串和整數:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
要將整數轉換為字符串,請將整數傳遞給 str()
功能:
number = 6
lang = "Python"
quote = "There are " + str(number) + " relational operators in " + lang + "."
print(quote)
現在,當您運行代碼時,它將成功執行:
There are 6 relational operators in Python.
還有其他方式來連接字符串和數字。
內置的字符串類提供了一個 format()
使用任意位置和關鍵字參數集格式化給定字符串的方法:
number = 6
lang = "Python"
quote = "There are {} relational operators in {}.".format(number, lang)
print(quote)
There are 6 relational operators in Python.
在Python 3.6及更高版本上,您可以使用f字符串,即以’f’為前綴的文字字符串,其中的括號內包含表達式:
number = 6
lang = "Python"
quote = f"There are {number} relational operators in {lang}."
print(quote)
There are 6 relational operators in Python.
最後,您可以使用舊的%格式:
number = 6
lang = "Python"
quote = "There are %s relational operators in %s." % (number, lang)
print(quote)
There are 6 relational operators in Python.
結論#
在Python中,您可以使用以下命令將整數轉換為字符串 str()
功能。
如果您有任何疑問或反饋,請隨時發表評論。
蟒蛇