Introduction to Python String Formatting
Python String Formatting
String formatting allows you to create formatted strings by substituting values into placeholders within the string.
There are multiple ways to perform string formatting in Python.
Here are some commonly used methods:
Using the%
Operator
The %
operator can be used for simple string formatting. It allows you to substitute values into placeholders within a string using format specifiers.
As an example:
name = "John"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
Output:
My name is John and I am 30 years old.
In this example:
%s
is a placeholder for a string value, and%d
is a placeholder for an integer value.- The values
(name, age)
are provided after the%
operator in parentheses.
Using the format()
Method
The format()
method is a more versatile way to perform string formatting. It allows you to use placeholders and provide values directly or by referencing variables.
As an example:
name = "John"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output:
My name is John and I am 30 years old.
In this example:
- The placeholders
{}
are used within the string. - The values
(name, age)
are passed to theformat()
method as arguments. - The
format()
method replaces the placeholders with the corresponding values.
Using f-strings (Formatted String Literals)
Starting from Python 3.6, f-strings provide a concise and readable way to perform string interpolation.
With f-strings, you can directly embed expressions and variables inside curly braces within a string.
As an example:
name = "John"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
Output:
My name is John and I am 30 years old.
In this example:
- The expressions
{name}
and{age}
are directly embedded within the string using f-string syntax. - The values of the variables
name
andage
are automatically substituted in place.