Hokhy Tann
Hokhy Tann

Reputation: 1248

How double %% Python Placeholder works

I don't understand why the output of the following code is 1%3. Can anyone explain this?

print '%d%%%d' %(1%2, 3%4)

Upvotes: 1

Views: 3372

Answers (1)

Riccardo Petraglia
Riccardo Petraglia

Reputation: 2023

The symbol % when used between integer, give the modulo:

1%2 = 1
2%2 = 0
2%3 = 1

This is the rest that remains when you divide the two numbers.

When used inside a string, the % has a particular meaning: in your case %d is an integer number (can be any number of digits). %% will be printed as %: the first % works as an escape sequence. Then you have another %d. The two %d are replaced by the number resulting from the operations 1%2, 3%4 which are, respectively, 1 and 3 because 4/3 = 0 with a rest of 3. Analougus for the 1%2: 2/1 = 0 with a resto of 1.

Upvotes: 2

Related Questions