5

I am working with a HTML application with Python. I usually use the % sign to indicate that I'm using a Python element, and never had a problem with that before.

Now, I am using some tables which I'm trying to control their size bye the percentage using the % sign. So now the Python does not show the Python elements.

Here is some code to explain myself:

<table width="90%">
<tr>
<td width="60%">HELLO</td>
<td width="40%">GOOD BYE</td>
</tr>
</table>

<input type="button" value="BUTTON" onclick="function(%s)" /> ''' % variable

The error that I am having says

unsupported format character '"' (0x22) at index 19"

making reference to the %s string in the onclick=function(%s)

Does someone know if the % sign in the tables affects Python or something like that?

Chris
  • 44,602
  • 16
  • 137
  • 156
mauguerra
  • 3,728
  • 5
  • 31
  • 37

2 Answers2

8

You need to escape '%' as '%%' in python strings. The error message you're getting probably is about the other percent signs. If you put only single percent sign in a string python thinks it will be followed by a format character and will try to do a variable substitution there.

In your case you should have:

'''

....
<table width="90%%">
<tr>
<td width="60%%">HELLO</td>
<td width="40%%">GOOD BYE</td>
</tr>
</table>

<input type="button" value="BUTTON" onclick="function(%s)" /> ''' % variable
soulcheck
  • 36,297
  • 6
  • 91
  • 90
3

In the newer Python (e.g., 2.6 or later), you can use .format() method. You will not need to escape your percent signs then:

s = '''<table width="90%">                                                                                
<tr>                                                                                                                                                                                                               
<td width="60%">HELLO</td>                                                                                                                                                                                         
<td width="40%">GOOD BYE</td>                                                                                                                                                                                      
</tr>                                                                                                                                                                                                              
</table>                                                                                                                                                                                                           
 <input type="button" value="BUTTON" onclick="function({funcarg})" /> '''

s.format(**{'funcarg': 'return'})
Roman Susi
  • 4,135
  • 2
  • 32
  • 47