Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Str.format() for Python 2.6 gives error where 2.7 does not

I have some code which works well in Python 2.7.

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import stdout
>>> foo = 'Bar'
>>> numb = 10
>>> stdout.write('{} {}\n'.format(numb, foo))
10 Bar
>>>

But in 2.6 I get a ValueError exception.

Python 2.6.8 (unknown, Jan 26 2013, 14:35:25) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import stdout
>>> foo = 'Bar'
>>> numb = 10
>>> stdout.write('{} {}\n'.format(numb, foo))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: zero length field name in format
>>>

When looking through the documentation (2.6, 2.7), I can see no mention of changes having been done between the two versions. What is happening here?

like image 806
Mogget Avatar asked Oct 29 '13 20:10

Mogget


People also ask

What does str format do in Python?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

What is the use of .2f in Python?

2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

What does %s %d mean in 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.

Does Python format call STR?

format doesn't call str()


1 Answers

Python 2.6 and before (as well as Python 3.0) require that you number the placeholders:

'{0} {1}\n'.format(numb, foo)

The numbering, if omitted in Python 2.7 and Python 3.1 and up, is implicit, see the documentation:

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

The implicit numbering is popular; a lot of examples here on Stack Overflow use it as it is easier to whip up a quick format string that way. I have forgotten to include them more than once when working on projects that must support 2.6 still.

like image 163
Martijn Pieters Avatar answered Sep 22 '22 19:09

Martijn Pieters