为什么int list没有在python 3.7及更高版本中转换但是在python 2.7上运行?

问题描述 投票:2回答:1

Python 2.7如下

>>> l1 =[1,2,3]
>>> for x in l1:
  str(x)


'1'
'2'
'3'
>>> 

为什么在python 3.7中int to str不会像上面2.7中看到的那样工作?

Python 3.7如下

>>> l1[1, 2, 3, 4]
>>> for x in l1:print(str(x))
Traceback (mostrecentcalllast):File <pyshell#593>", line 2, in <module>
     print(str(x))
     TypeError: 'str' object is not callable
python python-3.x python-2.7
1个回答
3
投票

这可能是因为您之前在某个时刻定义了变量str

>>> str = '3'
>>> str(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

您应该避免使用与内置函数(如str())相同的变量名称,否则可能会发生上述情况。

© www.soinside.com 2019 - 2024. All rights reserved.