aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Boris Muratov <[email protected]>2021-05-04 11:42:07 +0300
committerGravatar GitHub <[email protected]>2021-05-04 11:42:07 +0300
commite0ebd75ae61e18cac93fdac5896f2b97f2925eed (patch)
tree12452ea1c9b292bfbd11435ec57c32cdf174c8d5
parentMerge pull request #1556 from ToxicKidz/mod-ping-off-embed-timestamp (diff)
parentMerge 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.md28
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'
+```