Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in Python version earlier than 2.6

Tags:

python

format

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?

like image 601
user46646 Avatar asked Apr 27 '09 08:04

user46646


People also ask

When was format introduced in Python?

Summary. New string formatting was introduced in Python 3 and back ported to 2.7. This uses str. format() syntax.

How do you use %d strings in Python?

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.

What is %s and %D Python?

%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))


1 Answers

The str.format method was introduced in Python 3.0, and backported to Python 2.6 and later.

like image 112
SilentGhost Avatar answered Sep 20 '22 15:09

SilentGhost