String Formatting

Learn how to format strings in Python using format() and f-strings with examples.

Loading...
String Formatting

String formatting helps you build clean and readable text output, especially when working with variables, numbers, or dynamic content. It's widely used in logging, printing reports, and building user messages.

Python provides multiple ways to format strings, making it easier to create dynamic and readable text.

Using the format() Method

The format() method allows you to dynamically insert values into strings using placeholders ({}).

For example:

name = "Shefali"
country = "India"
text = "Hey my name is {} and I am from {}"
print(text.format(name, country))

Output:

Hey my name is Shefali and I am from India

Changing Order of Parameters

If you change the order of the given parameters, for example:

name = "Shefali"
country = "India"
text = "Hey my name is {} and I am from {}"
print(text.format(country, name))

Output:

Hey my name is India and I am from Shefali

To avoid mismatched values, you can specify the index of arguments.

For example:

name = "Shefali"
country = "India"
text = "Hey my name is {1} and I am from {0}"
print(text.format(country, name))

Output:

Hey my name is Shefali and I am from India

Named Placeholders

You can use named arguments in the format() method for clarity.

For example:

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

Output:

For only 49.00 dollars!

Here, {price:.2f} formats the value to 2 decimal places.

Dictionary Unpacking

You can also unpack a dictionary and pass it to format():

info = {"name": "Shefali", "country": "India"}
text = "My name is {name} and I am from {country}"
print(text.format(**info))

Output:

My name is Shefali and I am from India

Padding and Alignment

You can control spacing and alignment:

# Left align
print("{:<10}!".format("Python"))
 
# Right align
print("{:>10}!".format("Python"))
 
# Center align
print("{:^10}!".format("Python"))

Output:

Python    !
    Python!
  Python  !

Here,

  • text: the variable whose value will be inserted
  • :: starts the format specification
  • <: left-align the content
  • >: right-align the content
  • ^: center-align the content
  • 10: set the total field width to 10 characters

Using f-Strings

Introduced in Python 3.6, f-strings (formatted string literals) are prefixed with f and allow embedding expressions directly within the string.

Example 1:

name = "Shefali"
country = "India"
text = f"Hey my name is {name} and I am from {country}"
print(text)

Output:

Hey my name is Shefali and I am from India

Example 2: f-strings can evaluate expressions inline.

price = 49
txt = f"For only {price:.2f} dollars!"
print(txt)

Output:

For only 49.00 dollars!

Example 3: f-strings in a single statement

print(f"{2 * 30}") # output: 60

Padding and Alignment with f-Strings

You can use the same alignment options as with format():

text = "Python"
print(f"{text:<10}!")  # Left align
print(f"{text:>10}!")  # Right align
print(f"{text:^10}!")  # Center align

Output:

Python    !
    Python!
  Python  !

👉 Next tutorial: Python Docstrings

Support my work!