diff options
| -rw-r--r-- | bot/resources/tags/str-join.md | 9 |
1 files changed, 6 insertions, 3 deletions
diff --git a/bot/resources/tags/str-join.md b/bot/resources/tags/str-join.md index 6390db9e5..a6b8fb793 100644 --- a/bot/resources/tags/str-join.md +++ b/bot/resources/tags/str-join.md @@ -7,7 +7,8 @@ output = "" separator = ", " for color in colors: output += color + separator -print(output) # Prints 'red, green, blue, yellow, ' +print(output) +# Prints 'red, green, blue, yellow, ' ``` However, this solution is flawed. The separator is still added to the last element, and it is slow. @@ -15,11 +16,13 @@ The better solution is to use `str.join`. ```py colors = ['red', 'green', 'blue', 'yellow'] separator = ", " -print(separator.join(colors)) # Prints 'red, green, blue, yellow' +print(separator.join(colors)) +# Prints 'red, green, blue, yellow' ``` This solution is much simpler, faster, and solves the problem of the extra separator. An important thing to note is that you can only `str.join` strings. For a list of ints, you must convert each element to a string before joining. ```py integers = [1, 3, 6, 10, 15] -print(", ".join(str(e) for e in integers)) # Prints '1, 3, 6, 10, 15' +print(", ".join(str(e) for e in integers)) +# Prints '1, 3, 6, 10, 15' ``` |