7. Split and join
split() breaks a string into a list of strings. Its signature is:
sep— the separator text. Default:None, which splits on any run of whitespace and drops empty pieces.maxsplit— the maximum number of splits. Default:-1, which means no limit.
join() is the opposite: it puts a list of strings back together. It is called on the separator, with the list as its only argument:
iterable— a collection of strings, usually a list. Every element must be a string.
split() returns a new list; join() returns a new string. Neither changes the original.
Coming from JavaScript? join() is called on the separator, not the array: ",".join(words) instead of words.join(","). split() is the same as .split().
Split on a separator
split(sep) divides a string at every occurrence of sep and returns a list of the pieces.
Print the result of splitting "a,b,c" on ",".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Split on whitespace
Called with no arguments, split() divides the string at every run of whitespace. Several spaces in a row count as one separator, so no empty strings appear in the list.
Print the result of splitting "a b c" with no argument.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use a word from the list
split() returns a list, so you can index it like any other list.
Create a variable named words by splitting "Python is fun" with no argument. Then print the first word.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Limit the number of splits
The second argument of split(sep, maxsplit) is the maximum number of splits. With 1, the string is divided only at the first separator; the rest stays together.
Print the result of splitting "a-b-c" on "-" with a maxsplit of 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Join with a comma
join() is called on the separator and receives a list of strings. It returns one string with the separator between the elements.
Print the list ["a", "b", "c"] joined with the separator ", ".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Join with a hyphen
The separator is whatever string you call join() on. It can be more than one character.
Print the list ["2026", "10", "26"] joined with the separator "-".
Print exactly:
Create a free account to save your progress and unlock chapter 2.