Very stupid question about a % symbol

J

J

OK, this is a very stupid question about a very simple topic, but
Google is failing me this morning...

I'm trying to print a string that looks like this:

Reported memory amounts are within 10% tolerance

and the print line looks (for now) like this:

print "Reported memory amounts are within %s%s tolerance" %
(self.mem_tolerance,'%')

Is there a better way to print a '%' in the string when also using formating?

That works, but I've been looking for a way that looks... less kludgey.

I've tried things like this:

print "blahblahblah %s \%" % variable

but the first %s forces every other % to be interpreted as additional
format markers.

So while what I'm doing works, I was hoping someone could either
confirm that that's the right way, or show me a better way.

Cheers

Jeff
 
J

J

'Reported memory amounts are within 10% tolerance'

Thanks for the replies... I KNEW there was a simple way to escape the
% but I had no idea what it was (I just had conviction).

I was thrown when the \ didn't escape it... never knew about %%. But
now I do! Thanks for the replies!
 
T

Terry Reedy

Thanks for the replies... I KNEW there was a simple way to escape the
% but I had no idea what it was (I just had conviction).

I was thrown when the \ didn't escape it... never knew about %%. But
now I do! Thanks for the replies!

Doubling an escape char, whatever it is, is a common convention:print a {} format string line this: {2}
 
S

Steven D'Aprano

OK, this is a very stupid question about a very simple topic, but Google
is failing me this morning...
[...]

Others have already answered your question, but for future reference,
many people won't bother to read posts with a meaningless subject line
like "Very stupid question about ...".

Very stupid questions invite very stupid answers. I guess you can be
grateful that this Python group is more friendly than the average tech
group, otherwise you might have got no answers at all, or a sarcastic
one. Besides, your actual question isn't stupid at all. It is a sensible,
although basic, question.

A better subject line would have been:

"How to insert percent sign in % format strings?"

or some variation thereof. This will also be of benefit to others, who
some day may be Googling for the answer to the same question.


Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top