小能豆

What's the difference between %s and %d in string formatting?

py

I don’t understand what %s and %d do and how they work.


阅读 69

收藏
2023-11-28

共1个答案

小能豆

In Python, %s and %d are string formatting codes used in the context of the % operator to insert values into a string. They are placeholders that get replaced with the corresponding values provided after the % operator.

Here’s a brief explanation of %s and %d:

  1. %s (String Format Code):

  2. %s is a placeholder for string values.

  3. It is used to format a string with variables, where %s will be replaced by the string representation of the variable.

  4. Example:

    python name = "John" age = 25 print("My name is %s and I am %d years old." % (name, age))

    Output:

    python My name is John and I am 25 years old.

  5. %d (Decimal Integer Format Code):

  6. %d is a placeholder for decimal (integer) values.

  7. It is used to format a string with variables, where %d will be replaced by the decimal representation of the variable.

  8. Example:

    apples = 5 bananas = 3 total_fruits = apples + bananas print("I have %d apples and %d bananas. Total fruits: %d" % (apples, bananas, total_fruits))

    Output:

    I have 5 apples and 3 bananas. Total fruits: 8

  9. General Usage:

  10. The values to be inserted into the string are provided in a tuple after the % operator.

  11. The order of the values in the tuple corresponds to the order of the placeholders in the string.

  12. Alternative Format (using f-strings in Python 3.6 and above):

  13. Since Python 3.6, f-strings provide a more concise and readable way to achieve the same result. The above examples can be written using f-strings:

    print(f"My name is {name} and I am {age} years old.") print(f"I have {apples} apples and {bananas} bananas. Total fruits: {total_fruits}")

    F-strings use curly braces {} to embed expressions inside string literals directly.

In practice, f-strings are often preferred for their readability and conciseness, especially in modern Python code. However, the % formatting style is still valid and widely used, especially in older code or when working with versions of Python that do not support f-strings.

2023-11-28