Skip to content

Module 7 · Strings — topic 13 of 22

split()

split() breaks a string into a list of parts. Learn the difference between splitting on whitespace and on a separator, maxsplit, rsplit(), splitlines() and handling empty fields.

Beginner 12 min read·Lesson 94 of 306 in Python Programming

Learning objectives

  • Split text into words or fields
  • Use maxsplit and rsplit for partial splits
  • Handle empty fields and line breaks

Definition

split() breaks a string into a list of parts. Learn the difference between splitting on whitespace and on a separator, maxsplit, rsplit(), splitlines() and handling empty fields.

Introduction

split() cuts a string into pieces and returns them as a list. With no argument it splits on whitespace into words; with a separator such as "," it splits a line of data into fields.

Why it matters

Text arrives in lines and fields: CSV rows, log entries, commands typed by users, sentences to count. split() is the first step in turning raw text into structured data your program can work with.

Detailed explanation

Choosing the right separator is the most important decision when splitting. Data exported from spreadsheets often uses commas or tabs, log files may use spaces or pipes (|), and dates use hyphens or slashes. Look at a real sample of the data before writing the split, and check what happens when a field is empty or contains the separator itself.

split() never modifies the original string; it returns a new list, which you can then index, loop over, unpack or convert.

split() with no argument splits on any run of whitespace and ignores leading and trailing whitespace, so " a b ".split() is ["a", "b"].

split(sep) splits exactly at each occurrence of sep. Consecutive separators produce empty strings: "a,,b".split(",") is ["a", "", "b"].

maxsplit limits the number of splits: "k=v=w".split("=", 1) is ["k", "v=w"].

rsplit(sep, maxsplit) splits from the right, useful for file extensions: "archive.tar.gz".rsplit(".", 1).

splitlines() splits text into lines and handles \n, \r\n and other line endings.

The result is always a list of strings; convert numeric fields yourself.

split() is the inverse of join(): sep.join(text.split(sep)) recreates the original.

Syntax

Python
words = sentence.split()
fields = line.split(",")
key, value = item.split("=", 1)
lines = text.splitlines()
  • No argument: split on whitespace.
  • A separator splits at that exact text.
  • maxsplit limits the number of pieces.

Code examples

Words and fields

Python
print(" learn python today ".split())
print("Asha,82,Pune".split(","))
print("a,,b".split(","))
Output
['learn', 'python', 'today']
['Asha', '82', 'Pune']
['a', '', 'b']

maxsplit and rsplit

Python
print("key=value=extra".split("=", 1))
print("archive.tar.gz".rsplit(".", 1))
print("one\ntwo\r\nthree".splitlines())
Output
['key', 'value=extra']
['archive.tar', 'gz']
['one', 'two', 'three']

More examples

Parsing a small data file

Python
data = """name,subject,marks
Asha,Maths,82
Ben,Maths,67
Asha,Physics,91
"""
lines = data.splitlines()
header = lines[0].split(",")
totals = {}
for line in lines[1:]:
name, subject, marks = line.split(",")
totals[name] = totals.get(name, 0) + int(marks)
print(header)
print(totals)
print("Words in header:", len(" ".join(header).split()))
Output
['name', 'subject', 'marks']
{'Asha': 173, 'Ben': 67}
Words in header: 3

Step-by-step explanation

  • splitlines() turns the multi-line text into a list of lines; the trailing newline doesn’t add an empty line.
  • The first line is split into the header fields.
  • Each data line is split into three fields and unpacked into names.
  • totals adds marks per student, starting from 0 with get().

Expected output

Running “Parsing a small data file” prints exactly:

TextOutput
['name', 'subject', 'marks']
{'Asha': 173, 'Ben': 67}
Words in header: 3

Practical applications

  • CSV and log parsers split each line on commas, tabs or spaces.
  • Command-line programs split typed commands into words.
  • Search engines split queries into terms.

Best practices

  • Use split() with no argument for words.
  • Use maxsplit when values may contain the separator.
  • Use the csv module (Module 13) for real CSV files with quotes.

Common mistakes

Splitting on " " instead of whitespace

Avoid

"a b".split(" ") # ['a', '', 'b']

Prefer

"a b".split() # ['a', 'b']

split(" ") treats each single space as a separator and keeps empty strings.

Unpacking a split with the wrong number of fields

Avoid

name, mark = "Asha,82,Pune".split(",")

Prefer

name, mark, city = "Asha,82,Pune".split(",")

The number of names must match the number of pieces, or ValueError is raised.

Key takeaways

  • split() returns a list of substrings.
  • No argument splits on whitespace; a separator splits exactly.
  • maxsplit, rsplit and splitlines handle special cases.

Try it yourself

  1. 1
    Count the words in a sentence typed by the user.
  2. 2
    Split "10:30:45" into hours, minutes and seconds and convert them to total seconds.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic