How to use the % operator in Python

In Python, the % symbol is used for string formatting operations, also known as string formatting operator. It has two main uses:

  1. String formatting:
  2. Replaces placeholders in a string. For example, “Hello, %s!” % “Alice” will output “Hello, Alice!”.
  3. Different placeholders can be used, such as:

    %s for strings
    %d for integers
    %f for floating-point numbers
    %r for raw data

  4. Multiple placeholders can be used, and the corresponding replacement values need to be provided after the “%” symbol in the string. For example, “My name is %s, I am %d years old.” % (“Bob”, 25) will output “My name is Bob, I am 25 years old.”
  5. Number formatting:
  6. “The result is %.2f” is used to format the display of numbers, for example, “% 3.14159” would output “The result is 3.14”.
  7. You can specify the number of decimal places by using the .nf after the % symbol, where n represents the number of decimal places. For example, “The result is %.4f” % 3.14159 will output “The result is 3.1416”.
  8. You can use other format options, such as:

    %d: represents integers.
    %e: represents scientific notation.
    %g: represents general format.

  9. You can replace values by using %(value) after the percentage symbol, where value is the value to be replaced. For example, “The result is %(value).2f” % {“value”: 3.14159} will output “The result is 3.14”.

It’s important to note that in Python versions 3.6 and above, you can also use a more concise method for string formatting called f-strings. For example, with name = “Alice”; f”Hello, {name}!” will output “Hello, Alice!”.

bannerAds