Multiline parsing of python compiler demistification needed

Peter Otten __peter__ at web.de
Thu Jun 16 04:55:12 EDT 2016


Yubin Ruan wrote:

> Hi, everyone, I have some problem understand the rule which the python
> compiler use to parsing the multiline string.
> 
> Consider this snippet:
> 
> str_1 = "foo"
> str_2 = "bar"
> 
> print "A test case" + \
>        "str_1[%s] " + \
>        "str_2[%s] " % (str_1, str_2)
> 
> Why would the snippet above give me an "TypeError: not all arguments
> converted during string formatting" while the one below not ?
> 
> print "A test case" + \
>        "str_1[%s] " % str1
> 
> Obviously the first snippet have just one more line and one more argument
> to format than the second one. Isn't that unreasonable ? I couldn't find
> any clue about that. Anyone help ?
> 
> I am using python 2.7.6
> 

It doesn't matter into how many lines you break your statement. The % 
operator has higher precedence than +, so

a + b % c

is evaluated as a + (b % c). When c is a 2-tuple and b contains only one 
"%s" that inevitably fails:

>>> "%s" + "%s" % (1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

> Also, I know the **Pythonic** way to play with multiline, which would be
> using triple quote or a pair of parenthesis to surround the multiline
> string to make it a **online** string. You don't have to show code in that
> respect.

Did you know that adjacent string literals are merged into one? Compare:

>>> print "foo" + \
...       "%s" + \
...       "%s" % (1, 2)
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: not all arguments converted during string formatting
>>> print "foo" \
...       "%s" \
...       "%s" % (1, 2)
foo12





More information about the Python-list mailing list