-2

According to python 3 document, the string formating "%%" means "a perncet sign".

Following code is an example:

"%g%%" % 10.34 == "10.34%"

I am not sure what does this "%g" mean here, I suspect it should have the same meaning as "%g" in string formating, which is "Shorter one among %f or %e". and "%f" or "%e" means "floating point real number" or "Exponential notaion, lowercase'e'". Example of them are:

"%f" % 10.34 == '10.34000'

or

"%e" % 1000 == '1.000000e+03'

Based on this understanding, I tried follwoing code. I treid to formatting x first, and then directly use formating string "%%", but it does not work.

x = '%g' % 10.34
print(isinstance(x, float)) #this returns false
"%%" % x == "10.34%" # this returns error

I then tried this:

x = float(10.34)
print(isinstance(x, float)) #this returns true
"%%" % x == "10.34%" # this returns error as well

I even tried this:

x = "10.34000"
"%%" % x == "10.34%" # this returns error as well

Anyone know what is going on here with "%%". What its mean, do we have to use "%g%%" together with "%%" in any circumstance?

This is solved, the question comes from the misleading of the book. I made comments here: enter image description here

CuteMeowMeow
  • 91
  • 1
  • 9
  • 1
    If `%` is a meta character, how would you include an actual `%` in the *output* of the formatting result? The answer is `%%`. The `%%` sequence doesn't format any other values, it formats the `%` in the output. – Martijn Pieters Sep 27 '18 at 12:41
  • Yes. you are right. I now understand. "%%" is not a format but a way to output sign "%". Therefore we must include a format when using "%%", this format can be "%d", "%f" or "%s" etc.. – CuteMeowMeow Sep 27 '18 at 12:47
  • **If** you use the string as a template for printf-style formatting with the `%` operator, then `%` characters in the template string have special meaning. You can use `%%` without other metacharacters: `"This works: %%" % ()`, but that's a bit pointless, right? – Martijn Pieters Sep 27 '18 at 12:48
  • Yes. you are right. – CuteMeowMeow Sep 27 '18 at 12:54

1 Answers1

7

Since % introduces a format, there must be some way to specify a literal %; that way is %%.

>>> print("%s%%" % "foo")
foo%

It's analogous to how \\ specifies a literal backslash in a string.

chepner
  • 497,756
  • 71
  • 530
  • 681