Python: % Operator in Print() Statement

I just came across this Python code, my question is about the syntax in the print statement:

class Point(object):
    """blub"""
    #class variables and methods

blank = Point
blank.x = 3.0
blank.y = 4.0    
print('(%g,%g)' % (blank.x,blank.y))

This print statement simply prints (3.0, 4.0), i.e. the values in blank.x and blank.y.

I don't understand the % operator in front of the (blank.x, blank.y) in the last line. What does it do and where can I find it in the documentation?

Googling this, I always end up with the modulus operator.

1

3 Answers

Intro

The % operator in python for strings is used for something called string substitution. String and Unicode objects have one unique built-in operation: the % operator (modulo).

This is also known as the string formatting or interpolation operator.

Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language.

If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.


Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.