Skip to main content

Section 4.12 Strings and Lists

Two of the most useful methods on strings involve lists of strings. The split method breaks a string into a list of words. By default, any number of whitespace characters is considered a word boundary.
An optional argument called a delimiter can be used to specify which characters to use as word boundaries.
Notice that the delimiter doesn’t appear in the result.
The inverse of the split method is join. You choose a desired separator string, (often called the glue) and join the list with the glue between each of the elements.
The list that you glue together (wds in this example) is not modified. Also, you can use empty glue or multi-character strings as glue.
index Method in Lists and Strings
One important thing to note is that even though index methods is named the same in the context of strings and lists, they behave differently. With strings, the index method looks for a substring (or a character), and returns the first instance of that character. However, with lists, the index method looks for an element and returns the first instance of that element.
What happens when I split the string to a list?
BONUS: Check this example after reading the next section (List Type Conversion Function) and spot the difference!
Check your understanding

Checkpoint 4.12.1.

    What is printed by the following statements?
    myname = "Edgar Allan Poe"
    namelist = myname.split()
    init = ""
    str1 = namelist[0]
    str2 = namelist[1]
    str3 = namelist[2]
    init = init + str1[0] + str2[0] + str3[0]
    print(init)
    
  • Poe
  • Three characters but not the right ones. namelist is the list of names.
  • EdgarAllanPoe
  • Too many characters in this case. There should be a single letter from each name.
  • EAP
  • Yes, split creates a list of the three names.
  • William Shakespeare
  • That does not make any sense.
You have attempted of activities on this page.