StringsΒΆ

ConcatenationΒΆ

Use .join to to concatenate strings

names = ["Peter", "Albert", "Cleo", "Ember"]
output = ", ".join(names)

names = ["Peter", "Albert", "Cleo", "Ember"]
output = ""
for name in names:
    output += name
    if not is_last_element(name):
        output += ", "
# Good
names = ["Peter", "Albert", "Cleo", "Ember"]
output = ", ".join(names)

# Bad
names = ["Peter", "Albert", "Cleo", "Ember"]
output = ""
for name in names:
    output += name
    if not is_last_element(name):
        output += ", "

πŸ’‘ learnt from:

f-StringsΒΆ

Use f-String for simple placeholder expressions

output = f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}"

output = "Firstname: {}, Lastname: {}, Age: {}".format(
    user.first_name, user.last_name, user.age
)
# Good
output = f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}"

# Bad
output = "Firstname: {}, Lastname: {}, Age: {}".format(
    user.first_name, user.last_name, user.age
)

String.formatΒΆ

Use the string format function for complex expressions

template = """
{heading} - from: {date}
---------------------------------
{users}
"""
output = template.format(
    heading="User Overview",
    date=datetime.now().strftime("%Y-%m-%d"),
    users="\n".join(
        (
            f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}"
            for user in users
        )
    ),
)

heading = "User Overview"
date = datetime.now().strftime("%Y-%m-%d")
output = f"{heading} - from: {date}" + "\n"
output += "---------------------------------" + "\n"
for user in users:
    output += (
        f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}\n"
    )
# Good
template = """
{heading} - from: {date}
---------------------------------
{users}
"""
output = template.format(
    heading="User Overview",
    date=datetime.now().strftime("%Y-%m-%d"),
    users="\n".join(
        (
            f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}"
            for user in users
        )
    ),
)

# Bad
heading = "User Overview"
date = datetime.now().strftime("%Y-%m-%d")
output = f"{heading} - from: {date}" + "\n"
output += "---------------------------------" + "\n"
for user in users:
    output += (
        f"Firstname: {user.first_name}, Lastname: {user.last_name}, Age: {user.age}\n"
    )

πŸ’‘ learnt from: