When I run the following code in Python 2.5.2:
for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
I get:
Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format'
I don't understand the problem.
From dir('hello')
there is no format
attribute.
How can I solve this?
Summary. New string formatting was introduced in Python 3 and back ported to 2.7. This uses str. format() syntax.
The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.
%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))
The str.format
method was introduced in Python 3.0, and backported to Python 2.6 and later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With