Skip to main content

Section 9.9 Lists and strings

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:
Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid the letter “l” because it looks too much like the number “1”. So that's why I use “t”.
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:
Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.
You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:

Checkpoint 9.9.1.

    Q-4: What is printed by the following statements?
    myname = "Edgar Allan Poe"
    namelist = myname.split()
    init = ""
    for aname in namelist:
        init = init + aname[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. The for loop iterates through the names and creates a string from the first characters.
  • William Shakespeare
  • That does not make any sense.
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, “”, as a delimiter.

Checkpoint 9.9.2.

    Q-6: What would print when the following code executes?
    mylist = ['Hannah', 'Grace', 'Olivia', 'Ruth']
    delimiter = ''
    print(delimiter.join(mylist))
    
  • HannahGraceOliviaRuth
  • Because the delimiter is an empty string (not a space) the list would join without spaces.
  • Hannah Grace Olivia Ruth
  • The delimiter is an empty string, not a space.
  • Hannah, Grace, Olivia, Ruth
  • The delimiter is an empty string, it does not add spaces and commas automatically.
  • We would get an error
  • This will print without causing an error.

Checkpoint 9.9.3.

    Q-7: What would print when the following code executes?
    input = "Pat,Smith,girl,65 Elm Street,eat"
    pieces = input.split(",")
    print(pieces[3])
    
  • Smith
  • That's pieces[1].
  • girl
  • That's pieces[2]
  • 65 Elm Street
  • The address is at position 3 in the resulting list.
  • eat
  • That's pieces[4]
  • We would get an error
  • Why would this cause an error? We can use indices to get the element at an index in a list.