String Formatting

🔷 1. f-strings (Formatted String Literals) – Python 3.6+

Syntax:

f"some text {expression} more text"
  • Variables or expressions inside {} are evaluated at runtime.

  • You can use any valid Python expression inside the braces.

  • Faster and more readable than other methods.

Examples:

name = "Alice"
age = 30
height = 1.68

print(f"My name is {name}, I am {age} years old and {height:.2f} meters tall.")

Output:

My name is Alice, I am 30 years old and 1.68 meters tall.

Advanced formatting with f-strings:

pi = 3.1415926535
print(f"Pi to 3 decimal places: {pi:.3f}")
print(f"Binary of 10: {10:b}")
# Padded Output with zeros (5 digits): 00042
print(f"Padded number: {42:05d}")

🔷 2. str.format() Method – Python 2.7+ / 3.x

Syntax:

"string with placeholders {}".format(values)
Placeholder
Description

{}

Automatic

{0}, {1}

Positional

{name}

Keyword

Examples

# Positional arguments
print("Hello {}, you are {} years old.".format("Alice", 30))

# Indexed placeholders
print("Hello {0}, you are {1} years old. {0}, have a great day!".format("Alice", 30))

# Named arguments
print("Name: {name}, Age: {age}".format(name="Bob", age=25))

# Mixing types
pi = 3.14159
print("Pi is approximately {:.2f}".format(pi))  # Output: Pi is approximately 3.14

Padding and alignment:

# Width and alignment
print("{:<10}".format("left"))     # 'left      '
print("{:^10}".format("center"))   # '  center  '
print("{:>10}".format("right"))    # '     right'

Last updated