在Python中将整数转换为字符串
在Python中,可以使用内置的str()函数将整数转换为字符串。 str()函数接受任何Python数据类型并将其转换为字符串。但是使用str()并不是唯一的方法。这种类型的转换也可以使用“%s”关键字、 .format 函数或使用f-string函数。
以下是在Python中将整数转换为字符串的可能方法列表:
1. 使用 str()函数
Syntax: 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))
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))
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))
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))
2. 使用“%s”关键字
Syntax: “%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. 使用 .format()函数
Syntax: ‘{}’.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
Syntax: 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))