Percentage sign % in Python

In this tutorial, we will learn some interesting things about the percentage % sign in Python.

In Python, the percentage sign majorly does two things. They are:

  • It acts as a Modulo operator
  • It helps in string formatting

Let us understand each of them clearly.

Modulo operator

Similar to the addition (+), subtraction (-), multiplication (*) and division (/), the modulo (%) is also an arithmetic operator which evaluates the remainder of the division between two operands. These operands can be any integer or float.

Syntax: a % b

Let us suppose if the modulo operator is applied between two integers a and b i.e a%b, it calculates the remainder after dividing the first number a with the second number b.

Program:

a = 11
b = 2
c = a % b
print(c)

Output:

1

String formatting using % percentage sign

Similar to the other programming languages like C, the % percentage sign can be used to format the string. Hence, it is also known as the string formatting operator. Some of the placeholders in Python are:

  • %d – for integer
  • %f – for float
  • %s – for string
  • %o – for octal number
  • %x – for hexadecimal number

We need to use these placeholders in the string so that the desired variable replaces them in the resulting string with respect to the data type of variable.

The variables are must present immediately after a string followed by the % percentage sign.

Program:

a='Hello'
b=25
c=3.21
print("The value of a is %s"%a)
print("The value of b is %d"%b)
print("The value of c is %f"%c)
print("The hexadecimal value of b is 0x%x"%b)
print("The Octal value of b is %o"%b)

Output:

The value of a is Hello
The value of b is 25
The value of c is 3.210000
The hexadecimal value of b is 0x19
The Octal value of b is 31

From the above program, we can see that the variables of type String, Integer and Float replaced the placeholders %s, %d and %f in the string respectively.

Also, the integer variable b converted into hexadecimal and octal numbers using the %x and %o placeholders

If the string consists of more than one format specifier, then we can include the variable names in a tuple.

Example:

name='Ravi'
age=25
print("My name is %s and my age is %d" %(name,age))

Output:

My name is Ravi and my age is 25

Here, the variables must follow the order of their placeholders. Otherwise, the interpreter raises TypeError.

In some cases, to represent the percentages, we may need to print the percentage sign followed by an integer. At that point, the % percentage sign is used twice to escape.

Example:

result = "Ravi got 95"
print("%s%%" %result)

Output:

Ravi got 95%

That’s it! Hope you understood the use of the % percentage sign in Python. If you have any doubts, feel free to post them below.

Also, do check our other related articles,

Leave a Reply

Your email address will not be published.