MmmHmm
MmmHmm

Reputation: 3785

string formatting with modulus/percent sign

Is there something happening when string formatting that uses the modulus function while calling either

StringOperand % TupleOperand or

StringOperand % DictionaryOperand

Or is it just an arbitrary use of % for the string formatting function?

I'm guessing that the string formatting operator is not a call to modular arithmetic as the following:

tuple = (1,2,3)
print '%d %d %d'%tuple

prints: 1 2 3, but

print '%d %d %d %d'%tuple

returns TypeError: not enough args for format str

Upvotes: 2

Views: 2794

Answers (1)

Rudziankoŭ
Rudziankoŭ

Reputation: 11251

This is operator overloading. What you are talking about is language build-in, but you may overload methods on your own. Eg overload + operator that is decorated in python by __add__ method:

class YourMath(object):
    def __init__(self, param):
        self.param = param

    def __add__(self, x):
        return int(str(self.param) + str(x.param)) # concatenation 


x = YourMath(5)
y = YourMath(4)

+ will concatenate instead of sum up. Result of x+y in this case is 54.

Upvotes: 3

Related Questions