[Tutor] print method in Python2.7 problem

Steven D'Aprano steve at pearwood.info
Sun Mar 15 18:46:12 CET 2015


On Sun, Mar 15, 2015 at 12:46:04PM -0400, Doug Basberg wrote:
> Stat = {'Vbatt': 51.24, 'Ichrg': 6.75}
> print '   <td style="text-align: center;">SOLAR PANEL VOLTAGE</td>'
> print('    DSB "HI;" %s') % (str(Stat['Vbatt']))
> print('   <td style="width: 50%; text-align: center;">%s</td>') % (str(Stat['Vbatt']))

Yes? What about it? Do you have a question or do you expect us to read 
your mind?

If the second, this is your lucky day, because in fact I am a powerful 
psychic, and by reading your mind I can see that you are getting a 
ValueError exception from the last line:

ValueError: unsupported format character ';' (0x3b) at index 24


By using another of my superpowers, called "reading the error message", 
I can work out the nature of the problem: you have a format command "%;" 
which isn't supported.


When using string interpolation with the % operator, it looks for % 
formatting characters in the string. %s you already know. %d needs an 
integer value, %f a float. And %; isn't supported at all -- it is an 
error.

What you need to do is escape the percent sign, so it will be turned 
into a percent sign in the output, not treated as a format command in 
the input:

print('   <td style="width: 50%%; text-align: center;">%s</td>') % (str(Stat['Vbatt']))


-- 
Steve


More information about the Tutor mailing list