在Python中将整数转换为字符串

1580
14个回答

2333
>>> str(42)
'42'

>>> int('42')
42

文档链接:

str(x) 函数将任何对象 x 转换为字符串,通过调用 x.__str__() 方法实现,或者如果 x 没有定义 __str__() 方法,则使用 repr(x)


152

试试这个:

str(i)

69

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

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

str(a)

等同于

a.__str__()

同理,如果您想将某些内容转换为intfloat等类型,也可以使用此方法。


这个解决方案帮了我,我正在将一个字母数字混合的字符串转换为数字字符串,用ascii值替换字母,但是直接使用str()函数不起作用,但__str__()函数可以。例如(python2.7); s = "14.2.2.10a2" 不起作用的代码:print "".join([ str(ord(c)) if (c.isalpha()) else c for c in s ]) 起作用的代码:print "".join([ ord(c).str() if (c.isalpha()) else c for c in s ]) 期望输出:14.2.2.10972 - Jayant

20

处理非整数输入的方法:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

18
>>> 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

14

对于Python 3.6,你可以使用f-strings新特性将其转换为字符串,与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'>

如果您需要更详细的答案,可以查看这篇文章:将Python Int转换为String和将Python String转换为Int


这种方法的优点是它可以接受浮点数而不需要做任何更改 - 尽管它可能无法完全按照您想要的方式处理小数位。您可以明确指定如何处理小数,但这样它就不会再接受整数了。 - Karl Knechtel

13

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

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

8
您可以使用 %s.format
>>> "%s" % 10
'10'
>>>

或者:

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

8
我个人认为最好的方式是“ ”。
i = 32   -->    `i` == '32'

3
注意,这与repr(i)相当,因此对于长整数来说可能会很奇怪。(尝试使用i = `2 ** 32`; print i) - user4237459
20
这个功能在Python 2中已被弃用,在Python 3中完全被删除,所以我不建议再使用它了。 https://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax - teeks99

7

对于想要将整数转换为特定位数字符串的人,建议使用以下方法。

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

如需更多细节,您可以参考Stack Overflow问题“如何在数字前添加前导零”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接