Python % Operator: Modulus and Formatting

In Python, the % symbol is used as the operator for modulus operation and can also be used for string formatting.

  1. Modulo operation:
    The % operator can be used to calculate the remainder of dividing two numbers, known as modulo operation. For example, the result of 10 % 3 is 1, because the remainder of dividing 10 by 3 is 1.
  2. String formatting:
    The % operator can also be used for string formatting operations. Placeholders in the form of %s, %d, %f can be used in the string and then replaced with values using the % operator. For example:
  3. “My name is Alice, I am 25 years old, and my height is 165.5 cm.”
  4. The output is: “My name is Alice, I am 25 years old, and my height is 165.5 cm”. In this example, %s represents a string, %d represents an integer, and %f represents a floating point number, and these placeholders are replaced using the % operator.
bannerAds