String formatting error

为君一笑 提交于 2019-12-24 07:35:38

问题


Using the code print('{0} is not'.format('That that is not')) in Python 3.1.1, I get the following error:

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

when I delete the line Netbeans automatically inserted at the beginning:

from distutils.command.bdist_dumb import format

which itself causes an error of

ImportError: cannot import name format

What am I doing wrong here?


回答1:


You must be running an older version of Python. This does work in 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'

You will, however, get this error in 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'

This feature seems to have been backported to Python 2.6, so you won't get this error there. You must be running Python < 2.6.



来源:https://stackoverflow.com/questions/2450188/string-formatting-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!