Member-only story

Common Mistakes to Avoid with Template Strings in Python

Python Coding
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."

3. Avoid Mixing Too Many Placeholders:

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet