10.25. 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.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
An optional argument called a delimiter can be used to specify which
characters to use as word boundaries. The following example uses the string
ai
as the delimiter:
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.
Check your understanding
- 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.
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)