I don’t understand what %s and %d do and how they work.
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.
%s
%d
%
Here’s a brief explanation of %s and %d:
%s (String Format Code):
%s is a placeholder for string values.
It is used to format a string with variables, where %s will be replaced by the string representation of the variable.
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.
%d (Decimal Integer Format Code):
%d is a placeholder for decimal (integer) values.
It is used to format a string with variables, where %d will be replaced by the decimal representation of the variable.
apples = 5 bananas = 3 total_fruits = apples + bananas print("I have %d apples and %d bananas. Total fruits: %d" % (apples, bananas, total_fruits))
I have 5 apples and 3 bananas. Total fruits: 8
General Usage:
The values to be inserted into the string are provided in a tuple after the % operator.
The order of the values in the tuple corresponds to the order of the placeholders in the string.
Alternative Format (using f-strings in Python 3.6 and above):
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.