String Formatting in python
String formatting in Python is a way to embed expressions inside string literals, using placeholders or f-strings to dynamically generate strings. There are several ways to format strings in Python:
1. Using % Operator
This method is similar to C's printf style. You use % followed by a format specifier to insert values into a string.
python
Code
name = "Alice"
age = 30
formatted_string = "Hello, %s. You are %d years old." % (name, age)
print(formatted_string)
2. Using str.format()
The str.format() method allows more flexibility and is preferred over the % operator.
python
Code
name = "Bob"
age = 25
formatted_string = "Hello, {}. You are {} years old.".format(name, age)
print(formatted_string)
You can also use positional and keyword arguments:
python
Code
formatted_string = "Hello, {0}. You are {1} years old.".format(name, age)
print(formatted_string)
formatted_string = "Hello, {name}. You are {age} years old.".format(name="Charlie", age=35)
print(formatted_string)
3. Using f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are a concise and convenient way to embed expressions inside string literals.
python
Code
name = "Dave"
age = 40
formatted_string = f"Hello, {name}. You are {age} years old."
print(formatted_string)
4. Using Template Strings
The string.Template class in the string module provides another way to handle string formatting, which can be useful for internationalization and other applications.
python
Code
from string import Template
template = Template("Hello, $name. You are $age years old.")
formatted_string = template.substitute(name="Eve", age=45)
print(formatted_string)
Examples of Different Formatting Options
Aligning Text
python
Code
# Right align with width 10
print(f"{'Hello':>10}")
# Left align with width 10
print(f"{'Hello':<10}")
# Center align with width 10
print(f"{'Hello':^10}")
Formatting Numbers
python
Code
number = 1234.56789
# Two decimal places
print(f"{number:.2f}")
# Thousand separator
print(f"{number:,}")
# Percentage
print(f"{0.75:.0%}")
Padding and Truncating Strings
python
Code
string = "Python"
# Pad to 10 characters
print(f"{string:10}")
# Truncate to 3 characters
print(f"{string:.3}")
Advanced Formatting with str.format()
Nested Fields
python
Code
person = {'name': 'Frank', 'age': 50}
formatted_string = "Hello, {0[name]}. You are {0[age]} years old.".format(person)
print(formatted_string)
Accessing Attributes
python
Code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Grace", 55)
formatted_string = "Hello, {0.name}. You are {0.age} years old.".format(p)
print(formatted_string)
Summary
Use % operator for older Python versions.
Prefer str.format() for more flexibility and readability.
Use f-strings for concise and readable formatting in Python 3.6+.
Consider string.Template for simpler and safer templates, especially for user input.