Member-only story
Common Mistakes to Avoid with Template Strings in Python
2 min readOct 16, 2024
1. Avoid Using % Formatting:
The % formatting method is outdated and can be error-prone. It is not as flexible as other options.
Bad:
name = "Alice"
age = 30
greeting = "Hello, %s! You are %d years old." % (name, age)
Good:
name = "Alice"
age = 30
greeting = "Hello, {}! You are {} years old.".format(name, age)
2. Avoid Manually Concatenating Strings:
Manually concatenating strings with + or other operators can get messy and inefficient.
Bad:
greeting = "Hello, " + name + "! You are " + str(age) + " years old."
Good:
greeting = f"Hello, {name}! You are {age} years old."