Search code examples
pythonstringstring-substitution

Python %s substitution works until I concatenate strings - what am I doing wrong?


I'm creating HTML with Python, with boilerplate formatting and substituted text using %s (I'm using %s because I'm posting on codepad.org, which runs Python2, even though I'm testing this using Python3).

If I write a single block of HTML, with %s substitutions, it's all fine.

If I try to make it more flexible, and create the HTML in chunks, it doesn't work, even though it all looks the same to me.

I've simplified it to very short pieces of code - I'm clearly doing something wrong, but can't see it - help greatly appreciated!

print ('1abc %s def' % ('X')) # Line 1 - OK
string1 = '1abc %s def' % ('X')
print (string1) # Line 2 - OK

string2 = ("'2abc %s def'" + " % ('X')")
print (string2) # Line 3 - Not OK

Line 1: WORKS - output: 1abc X def

Line 2: WORKS - output: 1abc X def

Line 3: DOES NOT WORK - output: '2abc %s def' % ('X')


Solution

  • % (X,) can't be part of a string; it can be something you apply to the result of concatenating strings, however.

    That is to say, the following works fine:

    string2 = ("2abc " + "%s def") % ('X',) 
    print(string2)
    

    ...but the % is syntax here, not data. (Same for the "s!)