Python Formatting
Python provides several ways to format strings. Here are some common methods for string formatting in Python:
- Using the
%
operator:python
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)
Output: My name is Alice and I am 25 years old.
Using the str.format()
method:
python
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
Output: My name is Alice and I am 25 years old.
Using f-strings (formatted string literals):
python
name = "Alice" age = 25 message = f"My name is {name} and I am {age} years old." print(message)
Output:My name is Alice and I am 25 years old.
These methods allow you to insert values into a string by using placeholders or expressions enclosed in curly braces. The values are then provided either as arguments to the %
operator, the str.format()
method, or directly within the curly braces in the case of f-strings.
Additionally, you can specify formatting options within the placeholders to control the appearance of the output. For example, %s
is used for string substitution, %d
for integer substitution, and so on. With str.format()
, you can also specify format specifiers, such as {:.2f}
to format a floating-point number with two decimal places. F-strings provide a concise way of embedding expressions directly into the string, allowing you to perform computations and function calls within the placeholders.
Remember to choose the formatting method that best suits your needs and the version of Python you are using, as f-strings were introduced in Python 3.6.