01 / 07
Split at a separator into a list
Loops, and where your data lives
INPUT · Slides
01 / 07
split divides a string at a separator and gives you a list.
In the brackets you say what to divide on. The example below divides on a comma.
print("red,blue,yellow".split(","))Result
['red', 'blue', 'yellow']
02 / 07
What comes back is a list, which means everything you learned about lists works on it.
Take one out by number, count with len, go round with for. What was awkward while it was one string becomes easy the moment it is a list.
colours = "red,blue,yellow".split(",")print(colours[0])print(len(colours))Result
red 3
03 / 07
The separator does not have to be a comma. A space, or any character you like.
What people write tends to be divided by spaces, so split(" ") gets plenty of use.
text = "Grace Hopper"print(text.split(" "))Result
['Grace', 'Hopper']
04 / 07
The other direction is join. It runs the items of a list together into a single string.
The shape of the writing is a little unexpected, mind.
print(",".join(["red", "blue", "yellow"]))Result
red,blue,yellow
05 / 07
You will want to write colours.join(","), but Python has it the other way round. Put .join on the separator and hand it the list in the brackets.
The reason for the shape is that join is an instruction meaning "take me, and put me between them". The separator is the one doing the work.
To change the separator you change only the string in front. ", ".join(...) or "".join(...), as you please.
colours = ["red", "blue"]print(" and ".join(colours))print("".join(colours))Result
red and blue redblue
06 / 07
split and join go there and back. Split it into a list, work on it with the list tools, join it up again.
That is the standard round when you are reshaping a string. The example turns comma separated into "and" separated.
colours = "red,blue,yellow".split(",")print(" and ".join(colours))Result
red and blue and yellow
07 / 07
Look back over what this group covered.
name[0] … one character by number. Same as a listname[0:3] … cut a piece out by slicing. Same as a listin, find, count … searchingupper, strip, replace … working on it. The original does not changesplit, join … going to a list and backIndexing and slicing came over from lists untouched. Python is built so that "things in a row" take the same writing. Learn one and there is less to learn next time.