aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-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'
+```