diff options
| author | 2021-04-12 11:20:43 -0400 | |
|---|---|---|
| committer | 2021-04-12 11:20:43 -0400 | |
| commit | d0f6c92df65d551b12cc914f15bd20994729c7ce (patch) | |
| tree | fdfb82a434a2d9d85f09c96e09f6530c6120b4eb | |
| parent | Merge pull request #1516 from ToxicKidz/sorted-available-channels (diff) | |
Create str-join.md
Create a tag to showcase `str.join`
| -rw-r--r-- | bot/resources/tags/str-join.md | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/bot/resources/tags/str-join.md b/bot/resources/tags/str-join.md new file mode 100644 index 000000000..e8407ac26 --- /dev/null +++ b/bot/resources/tags/str-join.md @@ -0,0 +1,25 @@ +**Joining Iterables** + +Suppose you want to nicely display a list (or some other iterable). The naive solution would be something like this. +```py +colors = ['red', 'green', 'blue', 'yellow'] +output = "" +separator = ", " +for color in colors: + output += color + separator +print(output) # Prints 'red, green, blue, yellow, ' +``` +However, this solution is flawed. The separator is still added to the last color, and it is slow. + +The better way is to use `str.join`. +```py +colors = ['red', 'green', 'blue', 'yellow'] +separator = ", " +print(separator.join(colors)) # Prints 'red, green, blue, yellow' +``` +This method 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' +``` |