What is % in Python?

What is percent in python

In this article, we will cover what is % in Python and what are different ways to use % in Python.

In python, there are different types of operators with which we can perform different operations on any given data. In this article, we will discuss the % operator in python. We will also discuss the various applications of the % operator in python.

What is % Operator in Python?

The % operator is known as the modulo operator in python. It is a binary operator that operates on two operands. The syntax for the % operator is as follows.

Here, expression1 and expression2 must evaluate to a numeric value. The numeric value may be an integer, a floating-point number. After execution, “expression1 % expression2” returns the remainder when expression1 is divided by expression2.

For instance, 17%3 will evaluate to 2. This is so because when 17 is divided by 3, we get 2 as the remainder. To understand the working of the % operator in a better way, look at the following example.

Output:

The % Operator with strings in python

The % operator is also used for string formatting in python. There may be situations when we need to insert a variable into a string. In such situations, we use the % operator inside the strings as a placeholder for variables or to specify the format of the variables in the string. Suppose that you are given the name “Aditya” and the age “23” as variables. Now, we have to print the string "Aditya is 23 years old.“. We can use them in a string as discussed below.

The % Operator as a placeholder for variables  in python

For instance, suppose that we have to print the name and age of a person that has been given as variables name and age.  To fit the variables into the sentence, we will use the % operator as follows.

Here, inside the string, we have used the % operator as placeholders. The specifier %s shows that a string value will be placed at the place of %s. Similarly, %d will be replaced with an integer. 

The % operator when used outside the string, accepts a tuple of variables and inserts the values at the specified placeholders as follows.

Output:

Remember that the tuple containing the variables should have as many variables as the number of placeholders in the string. Otherwise, the program will run into a TypeError exception.

For instance, if the tuple of variables has more variables than the number of placeholders in the string, the program, on execution, will run into the TypeError exception as shown below.

Output::

Here, you can observe that the TypeError exception has been raised by the program with the message “TypeError: not all arguments converted during string formatting" when we tried to pass more variables than the number of placeholders in the string.

Similarly, when we pass a lesser number of variables in the tuple compared to the placeholders, the program will run into an error causing the TypeError exception as shown below.

Output:

Here, when we tried to pass a lesser number of variables than the number of placeholders in the string, the program raised the TypeError exception with the message “TypeError: not enough arguments for format string“.

You should also maintain the order of the variables in the tuple. The variables in the tuple should be compatible with the corresponding placeholder in the string. Otherwise, the program will run into a TypeError exception.

For instance, the %s specifier is used as a placeholder for string variables. Similarly, the %d specifier is used as a placeholder for the integers. If we pass an integer at the place of the string variable or a string in place of the integer, the program will run into a TypeError exception as shown below.

Output:

The % Operator as format specifiers in python

We can also use the % operator to specify the format of numbers in the strings. As discussed above, we can insert a variable into a string using the % operator. 

In the case of integers or strings, generally, we do not need to specify the format of the value. We simply insert the value from the variable using the placeholders. However, we might need to specify the width of the values for better alignment or to specify the number of digits in a floating-point value. In such cases, we can use the % operator to specify the format of the strings in python. The syntax for specifying the format is as follows.

Here, width is the total length the value from the variable can take. precision is the number of digits after the decimal point (in the case of numbers), and the type specifies the data type of the value in the variable that is inserted into the string. 

For instance, we can specify the formatting of a floating-point number using the % operator by limiting the number of digits to 2 and precision to 1 digit as follows.

Output:

We can also define the width of the string values using the width field. But precision is not defined for strings. 

Output:

In the above output, you can see that we have defined the width of the name to be 15. Hence, the name “Aditya” has been padded using spaces. However, if we define a width less than the actual string length, there is no effect on the string.

Output:

Here, you can observe that we have defined the width of the variable name to be 2 characters. However, “Aditya” consists of 6 characters. Hence, no change is observed in the output.

Conclusion

In this article, we have discussed the % operator in python. We also saw different applications and use cases of the % operator in python in formatting strings. 

That’s all about what is % in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!


import_contacts

You may also like:

Related Posts

  • Python copy file to another directory
    17 January

    How to copy file to another directory in Python

    Table of ContentsWays to copy file to another directoy in PythonUsing file handlingUsing the shutil libraryUsing the pathlib libraryUsing the os moduleUsing the subprocess moduleConclusion In this article, we will see different ways to copy file to another directory in Python. We can read and write files in Python. We can also work with paths […]

  • Check if variable is String in Python
    13 January

    Check if variable is String in python

    Table of ContentsHow to check if a given variable is of the string type in Python?Using the isinstance() function.Using the type() function.Check if function parameter is String In this post, we will see what is a string in Python and how to check whether a given variable is a string or not. There are many […]

  • Count the number of characters in a String in Python
    13 January

    Count number of characters in a string in python

    Table of ContentsWays to count the number of characters in a string in PythonUsing the len() functionUsing the for loopUsing the collections.Counter classConclusion In this post, we will see how to count number of characters in a String in Python. We can think of strings as a collection of characters, with every character at a […]

  • Pandas apply function to column
    12 January

    Pandas apply function to column

    Table of ContentsHow do I apply function to column in pandas?Using dataframe.apply() functionUsing lambda function along with the apply() functionUsing dataframe.transform() functionUsing map() functionUsing NumPy.square() function We make use of the Pandas dataframe to store data in an organized and tabular manner. Sometimes there, is a need to apply a function over a specific column […]

  • Copy file Python
    12 January

    How to Copy File in Python?

    Table of ContentsCopy file using the shutil module in PythonCopy file using the copyfileobj() function in PythonCopy file using the copyfile() function in PythonCopy file using the copy() function in PythonCopy file using the copy2() function in PythonCopy file using the operating system command in PythonCopy file using the os module in PythonCopy file using […]

  • 09 January

    Convert set to String in Python

    Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusion Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to string in Python […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.