Joining a List
split() turns a text into a list. The opposite, joining a list of texts into one text, is the method join(). It's written a little unusually: the method belongs to the separator, the text that goes between the elements, and the list goes in the parentheses:
names = ["Anna", "Tom", "Eva"]
print(", ".join(names))
print(" and ".join(names))
print("".join(names))This prints:
Anna, Tom, Eva
Anna and Tom and Eva
AnnaTomEvaRead ", ".join(names) as “join the names with a comma and a space”. The separator goes only between the elements, so there's no comma after Eva. Compare it with print(names), which shows ['Anna', 'Tom', 'Eva'] with brackets and quotes: join() gives you a clean text that you can show to people.
A common mistake is to write it the other way round, as with other methods: names.join(", "). A list has no method join(), so the program ends with AttributeError: 'list' object has no attribute 'join'.
join() can only join texts. With numbers in the list, it stops with an error:
scores = [12, 7, 30]
print(", ".join(scores))The program ends with this error:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
TypeError: sequence item 0: expected str instance, int foundThe message says that item 0 of the sequence (the list) should be a text, a str, but Python found a whole number, an int. The fix is to make a list of texts first, with str() in a loop:
scores = [12, 7, 30]
texts = []
for score in scores:
texts.append(str(score))
print(", ".join(texts))This prints 12, 7, 30.
Instructions
- 1
Print the guests on one line, separated by a comma and a space, after a label:
Guests: Anna, Tom, Eva, Max. Keep the lines with the two lists: the exercise also tries other lists in them. - 2
Print the scores as a sum, with
+between them, and its result:12 + 7 + 30 = 49. Join the scores with" + "(make texts of them first) and get the result withsum().