How do I format strings in Python (f-strings vs format vs %)?

Keywords: Python, String Formatting, f-strings, format function, percent formatting

In Python, string formatting can be achieved using three main methods: f-strings (formatted string literals), str.format() method, and percent (%) formatting. Each method serves the same purpose of embedding variables and expressions into strings, but they have different syntax and use cases.


# Example of string formatting

name = "Alice"
age = 30

# Using f-string (Python 3.6+)
formatted_str_f = f"Hello, my name is {name} and I am {age} years old."

# Using str.format()
formatted_str_format = "Hello, my name is {} and I am {} years old.".format(name, age)

# Using percent formatting
formatted_str_percent = "Hello, my name is %s and I am %d years old." % (name, age)

print(formatted_str_f)
print(formatted_str_format)
print(formatted_str_percent)
    

Keywords: Python String Formatting f-strings format function percent formatting