Python : String Formatting

String formatting in Python allows you to create dynamic strings by inserting variables and values into predefined placeholders within a string. There are multiple ways to format strings in Python, including using the % operator, the str.format() method, and f-strings (introduced in Python 3.6). Here's an overview of each method:

Using % Operator:


The % operator allows you to format strings using placeholders followed by a tuple of values:


name = "Alice"
age = 30
formatted_string = "Hello, %s! You are %d years old." % (name, age)
print(formatted_string)

 

In this example:

  • %s is a placeholder for a string value.
  • %d is a placeholder for an integer value.
  • The values (name, age) are passed as a tuple to replace the placeholders.

Using str.format() Method:


The str.format() method allows for more flexibility in formatting strings by using curly braces { } as placeholders:


name = "Bob"
age = 25
formatted_string = "Hello, {}! You are {} years old.".format(name, age)
print(formatted_string)

 

In this example, the curly braces { } act as placeholders for the values passed to the format() method.

Using f-Strings (Formatted String Literals):


f-strings provide a concise and readable way to format strings using variables directly within the string:


name = "Charlie"
age = 35
formatted_string = f"Hello, {name}! You are {age} years old."
print(formatted_string)

 

In f-strings, the expressions inside curly braces { } are evaluated and replaced with their values at runtime.

Formatting Options:


You can customize the formatting of values using various formatting options, such as specifying the number of decimal places for floats, padding strings with leading zeros, and aligning text within a specified width. Here are some examples:


pi = 3.14159
formatted_pi = f"The value of pi is {pi:.2f}"  # Two decimal places
print(formatted_pi)

number = 42
formatted_number = f"Number: {number:04}"  # Padded with leading zeros
print(formatted_number)

text = "Python"
formatted_text = f"{'{:<10}'.format(text)}"  # Left-aligned within 10 characters
print(formatted_text)

 

Using Named Arguments:


With f-strings and str.format(), you can use named arguments for more clarity and readability:


name = "David"
age = 40
formatted_string = f"Hello, {name}! You are {age} years old."
print(formatted_string)

Using named arguments
formatted_string = "Hello, {name}! You are {age} years old.".format(name=name, age=age)
print(formatted_string)

 

String formatting in Python provides a flexible and powerful way to create dynamic strings with variables and values. Each method has its advantages, so choose the one that best fits your coding style and requirements.