當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python integer轉string用法及代碼示例

在 Python 中,可以使用 內置 str() 函數將整數轉換為字符串。 str() 函數接受任何 python 數據類型並將其轉換為字符串。但使用 str() 並不是唯一的方法。這種類型的轉換也可以使用 “%s” 關鍵字、.format 函數或使用 f-string 函數來完成。以下是在 python 中將整數轉換為字符串的可能方法列表:

1.使用str()函數

用法:str(integer_value)

例:

Python3


num = 10
# check  and print type of num variable
print(type(num))
# convert the num into string
converted_num = str(num)
# check  and print type converted_num variable
print(type(converted_num))

2.使用“%s”關鍵字



用法: “%s” % integer

例:

Python3


num = 10
# check  and print type of num variable
print(type(num))
# convert the num into string and print
converted_num = "% s" % num
print(type(converted_num))

3. Using .format() function

用法:‘{}’.format(integer)

例:

Python3


num = 10
# check  and print type of num variable
print(type(num))
# convert the num into string and print
converted_num = "{}".format(num)
print(type(converted_num))

4. 使用 f-string

用法:f'{integer}’

例:

Python3


num = 10
# check  and print type of num variable
print(type(num))
# convert the num into string
converted_num = f'{num}'
# print type of converted_num
print(type(converted_num))




相關用法


注:本文由純淨天空篩選整理自RajuKumar19大神的英文原創作品 Convert integer to string in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。