Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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
AnnaTomEva

Read ", ".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 found

The 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. 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. 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 with sum().

Back

8/12

  1. 1. Upper and Lower Case
  2. 2. Trimming Spaces
  3. 3. Replacing Text
  4. 4. Quiz: Text Methods
  5. 5. Searching in Text
  6. 6. Beginnings and Ends
  7. 7. Splitting Text
  8. 8. Joining a List
  9. 9. Slices
  10. 10. Quiz: Slices
  11. 11. Decimal Places
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.