如何将整数转换为字符串?
42 ⟶ "42"
相反,请参见How do I parse a string to a float or int?。浮点数可以类似地处理,但处理小数点可能很棘手,因为浮点值不精确。有关更多具体建议,请参阅将浮点转换为字符串而不舍入。
如何将整数转换为字符串?
42 ⟶ "42"
相反,请参见How do I parse a string to a float or int?。浮点数可以类似地处理,但处理小数点可能很棘手,因为浮点值不精确。有关更多具体建议,请参阅将浮点转换为字符串而不舍入。
当前回答
对于Python3.6,您可以使用f-string新特性转换为string,与str()函数相比,它更快。它的用法如下:
age = 45
strAge = f'{age}'
Python为此提供了str()函数。
digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>
要获得更详细的答案,您可以查看本文:将PythonInt转换为String,将PythonString转换为Int
其他回答
对于Python3.6,您可以使用f-string新特性转换为string,与str()函数相比,它更快。它的用法如下:
age = 45
strAge = f'{age}'
Python为此提供了str()函数。
digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>
要获得更详细的答案,您可以查看本文:将PythonInt转换为String,将PythonString转换为Int
试试看:
str(i)
您可以使用%s或.format:
>>> "%s" % 10
'10'
>>>
Or:
>>> '{}'.format(10)
'10'
>>>
>>> str(42)
'42'
>>> int('42')
42
文档链接:
int()str()
str(x)通过调用x.__str__()将任何对象x转换为字符串,如果x没有__str__方法,则调用repr(x)。
>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5