1

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

kenlukas
  • 3,616
  • 9
  • 25
  • 36
seqandmore
  • 13
  • 4
  • 6
    The % is just a literal character inside a string in the last example. – jonrsharpe Aug 29 '19 at 18:04
  • 1
    you might be interested in a template library like Mako, which will allow not just substitutions but also loops and includes and so on, as well as offering protection against html injection – Eevee Aug 29 '19 at 18:17
  • A-yup. Personally, I (strongly!) recommend [Genshi](https://genshi.edgewall.org/), which -- unlike some other template engines -- isn't even *capable* of generating badly-formed output when in XML or HTML modes. – Charles Duffy Aug 29 '19 at 18:20

1 Answers1

4

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

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thank you! So the % is like a command, and I'm converting it to text? I agree - this now works, and I can hopefully move forward. – seqandmore Aug 29 '19 at 18:12