Torxed Torxed - 10 months ago 40
Python Question

%s formatting precedes + operator in joining two strings before formatting

Revived some old code and tried to refactor it to match Python7 and 3 standards.

A lot of string operations used the

"Something was %s in here" % "merged"

So I began the process of swapping this out for
, worked great until this row popped up:

cmd = 'cat %s[0-9] | - | ' % filename[:-2] + cmd

Now I thought I looked thoroughly at this and converted it into:

cmd = 'cat {}[0-9] | - | '.format(filename[:-2] + cmd)

Seeing as the command line was built upon further the last
didn't really trigger any warning signs.

However, lots of head scratching and debugging later I found out the correct conversion should be:

cmd = 'cat {}[0-9] | - | {}'.format(filename[:-2], cmd)

I'm aware that you probably should do
"%s" % ("x",) + cmd
here, but never the less, this was the code i was left with.

I asked colleagues and friends, they all assumed the same thing: "I guess the math operator precedes the function operator of joining the string".

That's obviously not the case and I'm wondering, is there a reason why
"%s" % "x"
goes before
+ "y"

Technically speaking to me the addition operation (purely speaking math wise here) should go before any function call?

Why does Python2 treat the addition as a second hand operation to the function of merging into a string?

Answer Source

Because the % string formatting operator shares precedence with the % remainder or modulus operator, which binds more tightly than the + addition operator. See all the operators in order of precedence here