我們可以使用 Python 內置的 str() 函數來轉換整數數據類型。此函數將任何數據類型作為參數,並將其轉換為字元串。但是我們也可以使用「%s」文本並使用。format()函數。下面是 str() 函數的語法。
語法-
str(integer_Value)
讓我們理解下面的例子。
示例- 1 使用 str()功能
n = 25
# check and print type of num variable
print(type(n))
print(n)
# convert the num into string
con_num = str(n)
# check and print type converted_num variable
print(type(con_num))
print(con_num)
輸出:
<class 'int'>
25
<class 'str'>
25
示例- 2 使用「%s」整數
n = 10
# check and print type of n variable
print(type(n))
# convert the num into a string and print
con_n = "% s" % n
print(type(con_n))
輸出:
<class 'int'>
<class 'str'>
示例- 3:使用。格式()功能
n = 10
# check and print type of num variable
print(type(n))
# convert the num into string and print
con_n = "{}".format(n)
print(type(con_n))
輸出:
<class 'int'>
<class 'str'>
示例- 4:使用 f 弦
n = 10
# check and print type of num variable
print(type(n))
# convert the num into string
conv_n = f'{n}'
# print type of converted_num
print(type(conv_n))
輸出:
<class 'int'>
<class 'str'>
我們已經定義了將整數數據類型轉換為字元串類型的所有方法。你可以根據自己的要求使用其中的一種。
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127515.html