-1

I thought that % (modulo) returned remainders from division but saw this working piece of code and now I'm confused.

Here's the code:

prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

stock = {
    "banana" : 6,
    "apple" : 0,
    "orange" : 32,
    "pear" : 15
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

My question is specifically about the last 3 lines. What does the % do here?

rocambille
  • 15,398
  • 12
  • 50
  • 68

2 Answers2

2

That is the old string formating operator used to add the values of the dictionaries to the string to be printed.

You can read more about it on the docs.

An example usage is

var = 10
var2 = 25.234
str_to_print = "The value of var is %d and of var2 is %0.2f" % (var, var2)

A lot of examples and usefull information is available here https://pyformat.info/

João Almeida
  • 4,487
  • 2
  • 19
  • 35
0

This is similar to the C printf format. Refer to João Almeida's for the docs

kameranis
  • 284
  • 1
  • 13