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

42   ⟶   "42"

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


当前回答

在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'>)


其他回答

对于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

我认为最体面的方式是“”。

i = 32   -->    `i` == '32'

对于希望将int转换为特定数字的字符串的人,建议使用以下方法。

month = "{0:04d}".format(localtime[1])

有关更多详细信息,您可以参考堆栈溢出问题显示带前导零的数字。

您可以使用%s或.format:

>>> "%s" % 10
'10'
>>>

Or:

>>> '{}'.format(10)
'10'
>>>

在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'>)