6.9 Splitting and Joining Strings

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period2 exercises2 graded tests

README.md

6.9 Splitting and Joining Strings

Read first in the book: 6.7 Concatenation and Repetition, 6.8 Count and Index.

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

song = "The rain in Spain..."
wds = song.split()
print(wds)

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:

song = "The rain in Spain..."
wds = song.split('ai')
print(wds)

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"

wds = ["red", "blue", "green"]
glue = ';'
s = glue.join(wds)
print(s)
print(wds)

print("***".join(wds))
print("".join(wds))

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

Exercise 1

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

Open the 01 folder and edit main.py. Run Tests checks it.

Exercise 2

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

Open the 02 folder and edit main.py. Run Tests checks it.

For teachers

6.9 Splitting and Joining Strings

Students read Foundations of Python Programming's “Splitting and Joining Strings” in CS Room and work through its 2 Python coding exercises (2 graded).

  • Time: 1 class period
  • Tests: 2 in 2 graded exercises, set up for you when you import the lesson

Reading first

Exercises

FolderGradingTests
01Autograded1
02Autograded1