如何将整数转换为字符串?

42   ⟶   "42"

相反,请参见How do I parse a string to a float or int?。浮点数可以类似地处理,但处理小数点可能很棘手,因为浮点值不精确。有关更多具体建议,请参阅将浮点转换为字符串而不舍入。


当前回答

试试看:

str(i)

其他回答

在Python=>3.6中,可以使用f格式:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>

Python中没有类型转换和类型强制。必须以显式方式转换变量。

要将对象转换为字符串,请使用str()函数。它适用于定义了__str__()方法的任何对象。事实上

str(a)

相当于

a.__str__()

如果您想将某些内容转换为int、float等,也是如此。

随着Python 3.6中f-string的引入,这也将起作用:

f'{10}' == '10'

它实际上比调用str()更快,代价是可读性。

事实上,它比%x字符串格式化和.format()更快!

在python中有几种将整数转换为字符串的方法。您可以使用[str(integer here)]函数、f-string[f“{integer here}”]、.format()函数[“{}”.format,甚至可以使用“%s”%关键字[“%s”%integer here]。所有这些方法都可以将整数转换为字符串。

参见以下示例

#Examples of converting an intger to string

#Using the str() function
number = 1
convert_to_string = str(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the f-string
number = 1
convert_to_string = f'{number}'
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  {}'.format() function
number = 1
convert_to_string = '{}'.format(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  '% s '% keyword
number = 1
convert_to_string = '% s '% number
print(type(convert_to_string)) # output (<class 'str'>)


试试看:

str(i)