The percentage output varies from time to time

Asked 2 years ago, Updated 2 years ago, 16 views

When you print out "%%", sometimes you get only one, sometimes you get two, and where does this difference come from?

I'm using Python 3.5.1.

test="Let's finish"

print("%%") #2 output here
print("%% output %s" %test) # 1 output here

Output:

%%
Let's print out a percentage and end it

python escaping

2022-09-22 22:12

1 Answers

The first one you wrote was not a format string, but a string, so both %% were printed out The second one you used is a format string, so it is interpreted that %% was used for % output.

The format string treats anything that starts with a % in the string as a substitution character. %d is treated as a number, %s as a letter, etc.

So if you write % you can see an error message saying that the format is wrong.

>>> print ("This is %" % 100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: incomplete format

The promised directive used by the user to output % within the format string is %%.


2022-09-22 22:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.