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']
4The 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
Print how many words
messagehas:Words: 5. Keep the lines withmessageandscores: the exercise also tries other texts in them. - 2
The text
scoresholds a player's points from four games. Split it at the commas, add up the points as whole numbers and printTotal: 67.