What split() does
The split() method cuts a string into pieces and returns them as a list of strings. It is how you turn a line of text into separate items you can count, loop over or convert to numbers. The only question is where to cut, and split() offers two ways to answer it.
Splitting on whitespace
With no argument, split() cuts at whitespace: spaces, tabs and newlines. Any run of whitespace counts as one separator, and whitespace at the start or end is ignored:
sentence = "hello world foo"
words = sentence.split()
print(words) # ['hello', 'world', 'foo']
print(len(words)) # 3
print(" a b \n c\t".split()) # ['a', 'b', 'c']
Python prints lists with single quotes around each string, which is why the output above does not use double quotes, although you write the strings in your code with either kind. Splitting an empty or all-blank string gives an empty list.
Splitting on a specific delimiter
Pass a string and split() cuts at every occurrence of exactly that text:
csv = "a,b,c"
parts = csv.split(",")
print(parts) # ['a', 'b', 'c']
This version is stricter than the whitespace one. Nothing is merged and nothing is skipped, so neighbouring delimiters produce empty strings:
print("a,,b".split(",")) # ['a', '', 'b']
print("a,b,".split(",")) # ['a', 'b', '']
print("".split(",")) # ['']
Note the last line: splitting an empty string on a delimiter gives a list with one empty string, whereas splitting it on whitespace gives an empty list. A delimiter of an empty string, "abc".split(""), is not allowed and raises ValueError: empty separator.
Limiting the number of splits
A second argument, maxsplit, caps how many cuts are made, starting from the left. The rest of the string stays together in the last item:
print("a,b,c,d".split(",", 2)) # ['a', 'b', 'c,d']
print("k=v=w".split("=", 1)) # ['k', 'v=w']
That is handy for text like key=value, where the value may itself contain the separator.
Working with the resulting list
Since the result is an ordinary list, everything you know about lists applies. You can index it, take its length and loop over it:
words = "hello world foo".split()
print(words[0], words[-1]) # hello foo
for word in words:
print(word)
hello foo
hello
world
foo
Pieces are always strings, even when they look like numbers. To do arithmetic, convert them:
print("1 2 3".split()) # ['1', '2', '3']
print([int(n) for n in "1 2 3".split()]) # [1, 2, 3]
The opposite operation is join(), which glues a list of strings back together with a separator between them: " ".join(words) gives "hello world foo" again.
Splitting into lines and on several delimiters
To split on a newline, pass "\n" as the delimiter, or use splitlines(), which does the same job and does not leave an empty piece after a final newline:
print("a\nb\nc".split("\n")) # ['a', 'b', 'c']
print("a\nb\n".splitlines()) # ['a', 'b']
print("a\nb\n".split("\n")) # ['a', 'b', '']
split() accepts only one delimiter at a time. If your text uses two, such as semicolons and commas, first make them the same with replace(), then split: "a;b,c".replace(";", ",").split(",") gives ['a', 'b', 'c'].
Common mistakes
- Splitting on a space instead of on whitespace.
"a b".split(" ")gives['a', '', 'b'], because each single space is a separator and two in a row leave an empty piece. Plainsplit()gives['a', 'b']. - Delimiters with extra spaces.
"a, b, c".split(",")leaves a leading space in the last two pieces:['a', ' b', ' c']. Usesplit(", ")when the separator really is a comma and a space. - Expecting numbers. The pieces of
"10 20".split()are the strings"10"and"20", so adding them gives"1020". - Expecting the original to change. Like all string methods,
split()leaves the string untouched and returns a new list.
The exercise, step by step
The lesson gives sentence set to "hello world foo" and asks you to break it into words.
- Choose the cut. The words are separated by spaces, and you want each word as an item, so no argument is needed: whitespace splitting is the default.
- Call
sentence.split(). It returns the list of three words. - Store it in
words. Assign the result to a new variable below the existing line.
sentence = "hello world foo"
words = sentence.split()
The variable words now holds ['hello', 'world', 'foo'].
Key takeaways
s.split()splits on any run of whitespace and ignores whitespace at the ends.s.split(delim)cuts at every occurrence ofdelimand keeps empty pieces.- The optional second argument limits the number of cuts.
- The result is a list of strings, so you can index it, loop over it and convert its items.