Python for beginners/collections
>>> sentence = "Python's name is derived from the television series Monty Python's Flying Circus."
Words are made up of characters, and so are strings in Python, like the string stored in the variable sentence above. For the sentence above, it might seem more natural for humans to describe it as a series of words, rather than as a series of characters. Say we want to access the first word in our sentence. If we type in:
>>> first_word = sentence
Python only prints the first character of our sentence. (Think about this if you do not understand why.) We can transform our sentence into a list of words (represented by strings) using the split() function as follows:
>>> words = sentence.split()
'split() is a function: functions provide small pieces of helpful, ready-made functionality that we can use in our own code. Here, we apply the split() function to the variable sentence and we assign the result of the function (we call this the 'return value' of the function) to the new variable words.
By default, the split() function in Python will split strings on the spaces between consecutive words and it will returns a list of words. However, we can pass an argument to split() that specifies explicitly the string we would like to split on. In the code below, we will split a string on commas, instead of spaces.
>>> song_string = "Jerusalema,ikhaya,lami"
>>> song_list = song_string.split(",")
The reverse of the split() function can be accomplished with join(), it turns a list into a string using spaces as a default. You can specify a 'delimiter' or the string you want to use to join the items.
>>> song_list = ["Jerusalema", "ikhaya", "lami"]
>>> song_string = ' '.join(song_list)
>>> delimiter = ","
>>> song_string = delimiter.join(song_list)
- Exercise: Insert one or more graphical elements in a songline