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

Hic*_*ick 1282 python string integer

我想在Python中将整数转换为字符串.我是徒劳地捣蛋:

d = 15
d.str()
Run Code Online (Sandbox Code Playgroud)

当我尝试将其转换为字符串时,它显示的错误就像int没有调用任何属性一样str.

Bas*_*ard 1985

>>> str(10)
'10'
>>> int('10')
10
Run Code Online (Sandbox Code Playgroud)

文档链接:

问题似乎来自这条线:str().

转换为字符串是使用builtin __str__()函数完成的,该函数基本上调用int()其参数的方法.


And*_*mbu 55

Python中没有类型转换和类型强制.您必须以明确的方式转换变量.

要转换字符串中的对象,请使用该str()函数.它适用于任何具有已__str__()定义方法的对象.事实上

str(a)
Run Code Online (Sandbox Code Playgroud)

相当于

a.__str__()
Run Code Online (Sandbox Code Playgroud)

如果要将某些内容转换为int,float等,则相同.


nik*_*nik 18

要管理非整数输入:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
Run Code Online (Sandbox Code Playgroud)

好吧,如果我使用你的最新代码并重写一下以使其与Python一起使用:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
Run Code Online (Sandbox Code Playgroud)

它给了我类似的东西:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
Run Code Online (Sandbox Code Playgroud)

这是字符串结果的第一个字符__CODE__.我们在这里做什么?


max*_*ori 14

>>> 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
Run Code Online (Sandbox Code Playgroud)


小智 13

对于 Python 3.6,您可以使用f-strings新功能转换为字符串,并且与 str() 函数相比速度更快。它是这样使用的:

age = 45
strAge = f'{age}'
Run Code Online (Sandbox Code Playgroud)

为此,Python 提供了 str() 函数。

digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>
Run Code Online (Sandbox Code Playgroud)

有关更详细的答案,您可以查看这篇文章:Converting Python Int to String and Python String to Int


Sup*_*ova 10

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

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
Run Code Online (Sandbox Code Playgroud)


小智 6

在我看来,最体面的方式是``.

i = 32   -->    `i` == '32'
Run Code Online (Sandbox Code Playgroud)

  • 这已在python 2中弃用,并在python 3中完全删除,所以我不建议再使用它了.https://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax (14认同)
  • 请注意,这相当于`repr(i)`,所以对于longs来说会很奇怪.(试试``i =`2**32`;打印i``) (3认同)

Sup*_*ova 6

可以使用%s.format

>>> "%s" % 10
'10'
>>>
Run Code Online (Sandbox Code Playgroud)

(要么)

>>> '{}'.format(10)
'10'
>>>
Run Code Online (Sandbox Code Playgroud)


Eug*_*ene 5

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

month = "{0:04d}".format(localtime[1])
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*ine 5

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

f'{10}' == '10'
Run Code Online (Sandbox Code Playgroud)

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

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