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

Splitting Text

A text often holds several values: the words of a sentence, or numbers separated by commas. The method split() splits a text into parts and returns them as a list. With nothing in the parentheses, it splits the text at the spaces:

sentence = "Python is   really fun"
words = sentence.split()
print(words)
print(len(words))

This prints:

['Python', 'is', 'really', 'fun']
4

The spaces themselves aren't in the list, and it doesn't matter how many there are between two words. The result is an ordinary list, so everything you know about lists works with it: len(words) is the number of words, words[0] the first word, and a for loop goes through them one by one.

When the parts are separated by something else, write that separator in the parentheses:

line = "12,7,30"
parts = line.split(",")
print(parts)

This prints:

['12', '7', '30']

Look at the quotes: the parts are texts, not numbers. split() only cuts the text into pieces and doesn't know that they're numbers. To calculate with them, turn each part into a number with int():

line = "12,7,30"
total = 0
for part in line.split(","):
    total += int(part)
print(total)

This prints 49. Without int(), total += part would end with TypeError: unsupported operand type(s) for +=: 'int' and 'str': Python can't add a text to a number. sum(parts) fails the same way.

With a separator, split() cuts exactly there and removes nothing else. "Anna, Tom".split(",") gives ['Anna', ' Tom'], with a space before Tom. Split at the whole separator, split(", "), or strip() each part.

Instructions

  1. 1

    Print how many words message has: Words: 5. Keep the lines with message and scores: the exercise also tries other texts in them.

  2. 2

    The text scores holds a player's points from four games. Split it at the commas, add up the points as whole numbers and print Total: 67.

Back

7/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.