YouTip LogoYouTip

Python3 f-strings and Formatting

f-strings (Python 3.6+)

f-strings provide a concise way to embed expressions inside string literals. They are faster and more readable than older formatting methods.

Basic Usage

name = "Alice"
age = 25

print(f"Hello, {name}!")
print(f"{name} is {age} years old")
print(f"Next year: {age + 1}")
print(f"Upper: {name.upper()}")

Format Specifications

pi = 3.14159265
print(f"Pi: {pi:.2f}")              # Pi: 3.14

num = 1234567
print(f"{num:,}")                   # 1,234,567

ratio = 0.856
print(f"Score: {ratio:.1%}")        # Score: 85.6%

Date Formatting

from datetime import datetime
now = datetime.now()
print(f"Date: {now:%Y-%m-%d}")
print(f"Time: {now:%H:%M:%S}")

Summary

  • f-strings are the preferred way to format strings in Python3
  • Use :.2f for decimal places, :, for thousands separator
  • Supports expressions and method calls inside curly braces
← Python3 Async ProgrammingPython3 Type Hints β†’