Skip to content

Use str.join()

Sourcery refactoring id: use-join


Use str.join() instead of for loop


all_hats = ""
for hat in my_wardrobe.hats:
    all_hats += hat.description


all_hats = "".join(hat.description for hat in my_wardrobe.hats)


The most straightforward way to concatenate strings in Python is to just use the + operator:

hat_description = hat.colour + hat.type

This is perfectly fine when you are joining together small numbers of strings (though f-strings are the best choice for doing more complicated string handling).

The problem with using + or += comes when they are used to concatenate large lists of strings. For example you might use them in a for loop like the 'Before' example. This is cumbersome to read, and also isn't very performant. A new string has to be created for every iteration in the for loop, which slows things down.

Luckily Python strings come with the join method to solve this problem.

This accomplishes the same task in one line and is quite a lot faster to boot. You can also add a separator in between each string easily, without having to worry about extra separators being added at the beginning or end of the result.

all_hats = ", ".join(hat.description for hat in my_wardrobe.hats)