Python split string
last modified November 19, 2026 Python 3.15
In this article we show how to split strings in Python.
Splitting cuts a string into parts at a separator. Python strings have several methods for this:
splitandrsplitreturn a list of parts, cut from the left or from the right,partitionandrpartitioncut the string once and return a 3-tuple,splitlinescuts the string at line boundaries.
For patterns rather than fixed separators there is re.split. The
opposite operation, joining a list of strings into one, is covered in
Python join string.
Splitting on whitespace
Called without arguments, split cuts the string at runs of
whitespace.
#!/usr/bin/python line = 'sky club cpu\tcloud\nwar' words = line.split() print(words) print(len(words)) text = ' falcon owl ' print(text.split())
Spaces, tabs, and newlines all count as whitespace, and several of them in a row act as one separator. Leading and trailing whitespace is ignored, so no empty strings appear in the result.
$ python split_words.py ['sky', 'club', 'cpu', 'cloud', 'war'] 5 ['falcon', 'owl']
Splitting on a separator
With the sep argument, the string is cut at every occurrence of
the given separator.
#!/usr/bin/python
line = 'sky,club,,cpu,cloud'
print(line.split(','))
line = 'sky, club, cpu, cloud'
print(line.split(','))
print(line.split(', '))
words = [word.strip() for word in line.split(',')]
print(words)
print('a b'.split(' '))
print('a b'.split())
An explicit separator behaves differently from the default whitespace
splitting. Two adjacent commas produce an empty string, and the spaces after
the commas stay in the words. We either include the space in the separator or
strip each word; stripping is more robust when the input is not consistent.
The last two lines show the difference on a double space: split(' ')
returns an empty field, split() does not.
$ python split_sep.py ['sky', 'club', '', 'cpu', 'cloud'] ['sky', ' club', ' cpu', ' cloud'] ['sky', 'club', 'cpu', 'cloud'] ['sky', 'club', 'cpu', 'cloud'] ['a', '', 'b'] ['a', 'b']
Empty strings
The two forms of split also differ when the string is empty.
#!/usr/bin/python
print(''.split())
print(' '.split())
print(''.split(','))
fields = ''.split(',')
print(len(fields), bool(fields))
try:
'sky club'.split('')
except ValueError as e:
print('error:', e)
Without a separator, an empty or blank string gives an empty list. With a
separator, it gives a list containing one empty string, which is truthy. Code
that checks if fields: after line.split(',') never
sees an empty list. An empty separator is not allowed; to split a string into
characters, use list, as shown later.
$ python split_empty.py [] [] [''] 1 True error: empty separator
Limiting splits with maxsplit
The maxsplit argument sets the maximum number of cuts. The rest
of the string is returned as the last part.
#!/usr/bin/python
line = 'sky, club, cpu, cloud, war, pot'
print(line.split(', ', 2))
print(line.split(', ', maxsplit=4))
setting = 'url = https://example.com/?q=a=b'
key, value = setting.split('=', 1)
print(key.strip())
print(value.strip())
print(' sky club cpu '.split(maxsplit=1))
Two cuts give three parts. The maxsplit argument can be passed by
position or by keyword. A limit of one is the usual way to split
key=value settings: the value may contain the separator itself,
here the = characters of a URL query. With the default whitespace
separator, the remainder keeps its inner spaces; only the leading whitespace
is skipped.
$ python maxsplit.py ['sky', 'club', 'cpu, cloud, war, pot'] ['sky', 'club', 'cpu', 'cloud', 'war, pot'] url https://example.com/?q=a=b ['sky', 'club cpu ']
Splitting from the right
The rsplit method starts cutting from the end of the string. It
only differs from split when maxsplit is given.
#!/usr/bin/python
line = 'sky, club, cpu, cloud, war, pot'
print(line.rsplit(', ', 2))
print(line.rsplit(', ', 2)[-2:])
files = ['photo.jpg', 'archive.tar.gz', 'README']
for name in files:
print(name.split('.', 1), name.rsplit('.', 1))
print(line.rsplit(', ') == line.split(', '))
With a limit of two, rsplit separates the last two words and
keeps the rest together. The file names show the practical difference:
split('.', 1) cuts at the first dot, so the extension of
archive.tar.gz is tar.gz; rsplit('.', 1)
cuts at the last dot. A name without a dot is returned as a one-element list.
For file paths, the pathlib module offers
suffix and suffixes.
$ python rsplit_parts.py ['sky, club, cpu, cloud', 'war', 'pot'] ['war', 'pot'] ['photo', 'jpg'] ['photo', 'jpg'] ['archive', 'tar.gz'] ['archive.tar', 'gz'] ['README'] ['README'] True
Unpacking the parts
When a string has a known number of fields, we unpack the list into variables.
#!/usr/bin/python
record = 'John Doe;gardener;1985'
name, job, year = record.split(';')
print(name, job, int(year))
full_name = 'John Ronald Reuel Tolkien'
first, *middle, last = full_name.split()
print(first, middle, last)
for row in ['Lucy;teacher;1990', 'Paul;driver']:
try:
name, job, year = row.split(';')
print(name, job, year)
except ValueError as e:
print(f'{row!r}: {e}')
The number of variables must match the number of parts; a starred variable
collects any extra parts into a list. A record with a missing field raises
ValueError, which we catch to report the bad line.
$ python unpacking.py John Doe gardener 1985 John ['Ronald', 'Reuel'] Tolkien Lucy teacher 1990 'Paul;driver': not enough values to unpack (expected 3, got 2)
partition and rpartition
The partition method cuts the string at the first occurrence of
the separator and returns a 3-tuple: the part before, the separator, and the
part after. The rpartition method cuts at the last occurrence.
#!/usr/bin/python
settings = ['host=example.com', 'port=8080', 'debug', 'path=/a=b']
for setting in settings:
key, sep, value = setting.partition('=')
if sep:
print(f'{key:6} {value}')
else:
print(f'{key:6} (no value)')
path = '/home/user/docs/report.txt'
folder, _, filename = path.rpartition('/')
print(folder, filename)
print('README'.rpartition('.'))
Unlike split, partition always returns three
values, so unpacking never fails. When the separator is missing, the separator
and the after-part are empty strings; we test sep to find out.
rpartition splits a path into a folder and a file name. When it
finds no separator, the whole string ends up in the last element.
$ python partition_text.py
host example.com
port 8080
debug (no value)
path /a=b
/home/user/docs report.txt
('', '', 'README')
Splitting lines
The splitlines method cuts the string at line boundaries. It
recognizes \n, \r\n, \r, and several
other characters, such as the form feed \x0c, the file separator
\x1c, and the Unicode line separator \u2028.
#!/usr/bin/python
text = 'sky\nclub\r\ncpu\rcloud\n'
print(text.splitlines())
print(text.split('\n'))
print(text.splitlines(keepends=True))
print('a\x0cb\x1cc\u2028d'.splitlines())
print('a\x0cb\x1cc\u2028d'.split('\n'))
print(''.splitlines(), ''.split('\n'))
Compared with split('\n'), splitlines handles
Windows and old Mac line endings and does not produce an empty last element
for the final newline. With keepends=True the line endings are
kept. Because it breaks on more than \n, splitlines
can cut data that contains form feeds or Unicode separators; for such input,
split('\n') is the exact choice.
$ python split_lines.py ['sky', 'club', 'cpu', 'cloud'] ['sky', 'club\r', 'cpu\rcloud', ''] ['sky\n', 'club\r\n', 'cpu\r', 'cloud\n'] ['a', 'b', 'c', 'd'] ['a\x0cb\x1cc\u2028d'] [] ['']
Reading lines from a file
In this example we read words from a file. The file contains an empty line.
sky cup blue bear rock
The file has five words and one empty line.
#!/usr/bin/python
with open('words.txt') as f:
lines = f.read().splitlines()
print(lines)
words = [line for line in lines if line]
print(words)
with open('words.txt') as f:
print([line.rstrip('\n') for line in f])
We read the whole file and split it into lines; a comprehension then drops
the empty line. Iterating over the file object reads it line by line, with
the newline at the end of each line, so we remove it with
rstrip('\n'). The iteration does not load the whole file into
memory, which matters for large files.
$ python read_lines.py ['sky', 'cup', '', 'blue', 'bear', 'rock'] ['sky', 'cup', 'blue', 'bear', 'rock'] ['sky', 'cup', '', 'blue', 'bear', 'rock']
Multiple separators with re.split
The string methods take a single fixed separator. When the separators vary,
we use re.split with a regular expression.
#!/usr/bin/python
import re
line = 'sky, club;cpu ; cloud,war'
print(line.split(','))
print(re.split(r'\s*[,;]\s*', line))
data = '12 kg, 3.5 kg; 40kg'
print(re.split(r'\s*kg[,;]?\s*', data))
print([e for e in re.split(r'\s*kg[,;]?\s*', data) if e])
The pattern \s*[,;]\s* matches a comma or a semicolon with any
surrounding whitespace. Like split with a separator,
re.split produces an empty string when the text ends with a
separator, so we filter it out. More on patterns, capture groups, and limits
is in Python re.split.
$ python regex_split.py ['sky', ' club;cpu ; cloud', 'war'] ['sky', 'club', 'cpu', 'cloud', 'war'] ['12', '3.5', '40', ''] ['12', '3.5', '40']
Characters and fixed-size chunks
Sometimes we need to split a string into characters or into pieces of a fixed length.
#!/usr/bin/python
from itertools import batched
word = 'falcon'
print(list(word))
print(word.split('a'))
digits = '4006123456789012'
print([digits[i:i+4] for i in range(0, len(digits), 4)])
print([''.join(chunk) for chunk in batched(digits, 4)])
dna = 'ATGCGTACGTTA'
print(' '.join(dna[i:i+3] for i in range(0, len(dna), 3)))
The list function turns a string into a list of characters;
split with a letter only cuts at that letter. For chunks, we
slice the string in steps, or use itertools.batched (Python 3.12)
and join each tuple of characters back into a string. The last line groups a
DNA sequence into codons.
$ python chars_chunks.py ['f', 'a', 'l', 'c', 'o', 'n'] ['f', 'lcon'] ['4006', '1234', '5678', '9012'] ['4006', '1234', '5678', '9012'] ATG CGT ACG TTA
Quoted fields
Splitting on a separator ignores quoting. Data where a field may contain the separator needs a parser that understands quotes.
#!/usr/bin/python
import csv
import shlex
line = 'Roger,"Smith, Jr.",driver'
print(line.split(','))
print(next(csv.reader([line])))
command = 'cp "my file.txt" backup/'
print(command.split())
print(shlex.split(command))
The name Smith, Jr. contains a comma, so split(',')
cuts it in two. The csv module handles quoted fields; see
Python CSV. For command lines,
shlex.split keeps a quoted file name with a space together, as
a shell would; it is used for building commands in
Python exec command.
$ python quoted_fields.py ['Roger', '"Smith', ' Jr."', 'driver'] ['Roger', 'Smith, Jr.', 'driver'] ['cp', '"my', 'file.txt"', 'backup/'] ['cp', 'my file.txt', 'backup/']
Splitting bytes
The bytes type has the same methods; the separator must be a
bytes object too.
#!/usr/bin/python
data = b'GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n'
request_line, *headers = data.split(b'\r\n')
print(request_line.split())
for header in headers:
if header:
name, _, value = header.partition(b': ')
print(name.decode(), '->', value.decode())
print(data.splitlines())
We split a raw HTTP request into lines at \r\n, then split the
request line into its three parts and each header at : . The
values are decoded to strings only for printing. See
Python bytes for more on the type.
$ python split_bytes.py [b'GET', b'/index.html', b'HTTP/1.1'] Host -> example.com [b'GET /index.html HTTP/1.1', b'Host: example.com', b'']
Word frequency
In this example we count the most common words in a text file.
The falcon flew over the hill. The owl sat on the old oak tree; the falcon saw the owl, and the owl saw the falcon. An old fox watched them both -- the fox, the owl, and the falcon.
The text contains punctuation, mixed case, and a double dash.
#!/usr/bin/python
import string
from collections import Counter
with open('story.txt') as f:
text = f.read()
words = []
for token in text.split():
word = token.strip(string.punctuation).lower()
if word:
words.append(word)
print(len(words), 'words')
counter = Counter(words)
for word, n in counter.most_common(5):
print(f'{word:8} {n}')
The whitespace split gives us tokens such as hill.
and tree;. We strip punctuation from both ends of each token and
lowercase it, so The and the count as one word. The
-- token becomes an empty string and is skipped.
Counter.most_common returns the five most frequent words.
$ python word_freq.py 38 words the 11 falcon 4 owl 4 old 2 saw 2
Parsing a log
The last example combines splitlines, split with
maxsplit, and partition to parse log records.
#!/usr/bin/python
from collections import defaultdict
log = '''\
2026-11-19 08:12:01 INFO login user=alice ip=10.0.0.5
2026-11-19 08:12:09 WARN failed login user=bob ip=10.0.0.7
2026-11-19 08:13:44 INFO logout user=alice
2026-11-19 08:15:02 ERROR disk full path=/var/log
2026-11-19 08:16:30 WARN failed login user=bob ip=10.0.0.7
'''
by_level = defaultdict(list)
for line in log.splitlines():
date, time, level, message = line.split(maxsplit=3)
fields = {}
words = []
for part in message.split():
key, sep, value = part.partition('=')
if sep:
fields[key] = value
else:
words.append(part)
by_level[level].append((time, ' '.join(words), fields))
for level, events in by_level.items():
print(level)
for time, text, fields in events:
print(f' {time} {text:13} {fields}')
Each line has a date, a time, and a level, followed by a free-form message;
maxsplit=3 keeps the message in one piece. We then split the
message into words and use partition('=') to recognize the
key=value fields. The events are grouped by level in a
defaultdict.
$ python parse_log.py
INFO
08:12:01 login {'user': 'alice', 'ip': '10.0.0.5'}
08:13:44 logout {'user': 'alice'}
WARN
08:12:09 failed login {'user': 'bob', 'ip': '10.0.0.7'}
08:16:30 failed login {'user': 'bob', 'ip': '10.0.0.7'}
ERROR
08:15:02 disk full {'path': '/var/log'}
Source
str.split – Python documentation
str.splitlines – Python documentation
In this article we have split strings in Python with split,
rsplit, partition, and splitlines. See
also Python join string,
Python strip string,
Python re.split, and
Python string.
Author
List all Python tutorials.