Sourcery refactoring id:
str.join() instead of
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
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
+= comes when they are used to concatenate large
lists of strings. For example you might use them in a for loop like the 'Before'
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)