6.9. Splitting and Joining Strings

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.

shows the phrase "leaders and best" being split on spaces

An optional argument called a delimiter can be used to specify which characters to use as word boundaries.

shows example of splitting "leaders and best" on "e"

The following example uses the string ai as the delimiter:

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

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.

shows process of a "/" separating the words "leaders", "and", "best"

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

Create a new list of the 6th through 13th elements of lst (eight items in all) and assign it to the variable output.

Create a variable output and assign to it a list whose elements are the words in the string str1.

You have attempted 1 of 6 activities on this page