Skip to main content
 首页 » 编程设计

python之字符串格式错误

2025年05月04日33oomusou

在 Python 3.1.1 中使用代码 print('{0} is not'.format('That that is not')),我得到以下错误:

AttributeError: 'str' object has no attribute 'format' 

当我删除 Netbeans 在开头自动插入的行时:

from distutils.command.bdist_dumb import format 

这本身会导致错误

ImportError: cannot import name format 

我在这里做错了什么?

请您参考如下方法:

您必须运行旧版本的 Python。这在 Python 3.1.1+ 中有效:

$ python3 
Python 3.1.1+ (r311:74480, Nov  2 2009, 14:49:22)  
[GCC 4.4.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> '{0} is not'.format('That that is not') 
'That that is not is not' 

但是,您将在 Python 2.5.4 中遇到此错误:

$ python2.5 
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03)  
[GCC 4.4.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> '{0} is not'.format('That that is not') 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'format' 

此功能似乎已向后移植到 Python 2.6,因此您不会在那里遇到此错误。您必须运行 Python < 2.6。