Python-String Formatting

String formatting is a powerful feature in Python that allows you to create and manipulate strings in various ways. It’s an essential tool for developers, as it helps in making the code more readable and maintainable. In this post, we’ll explore different string formatting methods in Python, along with examples and use cases.

Table of Contents

Using the % Operator

The % operator is one of the oldest ways to format strings in Python. It’s similar to the printf-style in C.

Example 1:

name = "Alice"
print("Hello, %s!" % name)

Output:

Hello, Alice!

Using the str.format() Method

The str.format() method is more modern and provides a more flexible way to format strings.

Example 2:

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

Output:

Hello, Bob! You are 30 years old.

Example 3: Positional Arguments

print("The numbers are {2}, {1}, and {0}".format(100, 200, 300))

Output:

The numbers are 300, 200, and 100

Example 4: Named Arguments

print("The numbers are {a}, {b}, and {c}".format(a=100, b=200, c=300))

Output:

The numbers are 100, 200, and 300

Using F-Strings (Python 3.6+)

F-strings are the newest way to format strings in Python, introduced in version 3.6. They provide a concise and readable way to embed expressions inside string literals.

Example 5:

name = "Charlie"
print(f"Hello, {name}!")

Output:

Hello, Charlie!

Example 6: Expressions Inside F-Strings

x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")

Output:

The sum of 10 and 20 is 30

Example 7: Formatting Numbers

pi = 3.14159265
print(f"The value of pi is {pi:.2f}")

Output:

The value of pi is 3.14

Example 8: Aligning Text

print(f"{'left':<10}{'center':^10}{'right':>10}")

Output:

left     center    right

Example 9: Dynamic Expressions

width = 10
precision = 2
value = 12.34567
print(f"The value is {value:{width}.{precision}f}")

Output:

The value is      12.35

Example 10: Date Formatting

from datetime import datetime
now = datetime.now()
print(f"The current date and time is {now:%Y-%m-%d %H:%M:%S}")

Output:

The current date and time is 2023-08-22 12:34:56

String Alignment

String alignment is a common task in string formatting where you align text to the left, right, or center within a given width. In Python, you can achieve string alignment using several methods, including the % operator, the str.format() method, and f-strings. Here’s how you can use each of these methods for string alignment:

1. Using the % Operator

You can use the % operator along with specific formatting codes to align strings.

  • Left Alignment:
  print("%-10s" % "left")
  • Right Alignment:
  print("%10s" % "right")

2. Using the str.format() Method

The str.format() method provides more flexibility for string alignment.

  • Left Alignment:
  print("{:<10}".format("left"))
  • Right Alignment:
  print("{:>10}".format("right"))
  • Center Alignment:
  print("{:^10}".format("center"))

3. Using F-Strings (Python 3.6+)

F-strings, introduced in Python 3.6, offer a concise way to perform string alignment.

  • Left Alignment:
  print(f"{'left':<10}")
  • Right Alignment:
  print(f"{'right':>10}")
  • Center Alignment:
  print(f"{'center':^10}")

String alignment is an essential aspect of formatting, especially when you want to create tabular data or align text in a specific way. By using the % operator, str.format(), or f-strings, you can easily align strings to the left, right, or center, providing a visually appealing and well-structured output.

Conclusion

Python offers various ways to format strings, each with its unique features and use cases. Whether you prefer the classic % operator, the flexible str.format(), or the concise f-strings, understanding these methods will enhance your coding skills and allow you to write cleaner and more efficient code.

Try Quiz

Tutorial