String Formatting in Python
String Formatting in Python
In Python, working with text (or strings) often involves inserting variables or values into predefined string templates. This process is called string formatting. It helps you produce readable and dynamic output, whether you’re displaying messages, logging data, or generating content.
% Operator
The % operator is one of the oldest ways to format strings in Python. It works similarly to how C-style printf works. You insert special format specifiers into the string, and the values are substituted accordingly.
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))
.format() Method
The str.format() method allows more control and readability than the % operator. You use curly braces {} as placeholders which get replaced by arguments passed to format().
name = "Bob"
age = 25
print("Name: {}, Age: {}".format(name, age))
f-Strings
Introduced in Python 3.6, f-strings (formatted string literals) offer a concise and readable way to embed expressions inside string literals using curly braces. They are prefixed with the letter f.
name = "Charlie"
age = 22
print(f"Name: {name}, Age: {age}")