Page 157 -
P. 157
split the string
The split() method cuts the string
rock_band
Imagine you have a string containing several words assigned to a variable. Think
of a variable as if it’s a labeled jar:
A variable, a “Al Carl
rock_band = "Al Carl Mike Brian"
A single variable is assigned... ...a single string, which labeled jar. Mike Brian" A string,
contained
contains four words.
in a variable
The rock_band string, like all Python strings, has a split() method that (jar).
returns a collection of substrings: one for each word in the original string.
Using a programming feature called multiple assignment, you can take
the result from the cut performed by split() and assign it to a collection of
variables: The right side of the
The left side of the (rhythm, lead, vocals, bass) = rock_band.split() assignment operator
contains the call to
assignment operator lists the split() method.
the variables to assign
values to.
Al Carl Mike Brian
rhythm bass
lead vocals
“Al" “Brian"
“Carl" “Mike"
Multiple variables... ...each with its own
stringed value.
Each of the return values from the split() on rock_band is assigned to its
own separately named variable, which allows you then to work with each word in
whatever way you want. Note that the rock_band variable still exists and that it
still contains the original string of four names.
Looks like you can use multiple assignment and split() to
extract the scores from the results.txt file.
122 Chapter 4