How to use the % in Python?

In Python, the percent sign (%) is used as a modulus operator, also known as a remainder operator. It is used to calculate the remainder of a number when divided by another number.

Here are some examples to demonstrate how to use the modulo operator (%).

  1. Modular arithmetic:
a = 10
b = 3
c = a % b
print(c)  # 输出为1,因为10除以3的余数是1
  1. Formatting string:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# 输出为"My name is Alice and I am 25 years old."

In this example, %s and %d are used as placeholders to indicate the type of variables to insert into the string. %s represents a string type, while %d represents an integer type. By using the % operator, we can insert the variables name and age into the string.

Apart from %s and %d, there are also other placeholders that can be used, such as %f for floating point number types, and %r to convert variables to string types.

Note: In Python 3, a more common method of string formatting is to use the .format() method, which provides a more flexible and readable way to format strings. It is recommended to use the .format() method instead of the % operator.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds