diff options
| author | 2021-05-04 11:42:07 +0300 | |
|---|---|---|
| committer | 2021-05-04 11:42:07 +0300 | |
| commit | e0ebd75ae61e18cac93fdac5896f2b97f2925eed (patch) | |
| tree | 12452ea1c9b292bfbd11435ec57c32cdf174c8d5 | |
| parent | Merge pull request #1556 from ToxicKidz/mod-ping-off-embed-timestamp (diff) | |
| parent | Merge branch 'main' into str-join-tag (diff) | |
Merge pull request #1520 from python-discord/str-join-tag
Create str-join.md
| -rw-r--r-- | bot/resources/tags/str-join.md | 28 |
1 files changed, 28 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..c835f9313 --- /dev/null +++ b/bot/resources/tags/str-join.md @@ -0,0 +1,28 @@ +**Joining Iterables** + +If you want to display a list (or some other iterable), you can write: +```py +colors = ['red', 'green', 'blue', 'yellow'] +output = "" +separator = ", " +for color in colors: + output += color + separator +print(output) +# Prints 'red, green, blue, yellow, ' +``` +However, the separator is still added to the last element, and it is relatively slow. + +A better solution is to use `str.join`. +```py +colors = ['red', 'green', 'blue', 'yellow'] +separator = ", " +print(separator.join(colors)) +# Prints 'red, green, blue, yellow' +``` +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' +``` |