Python String split(): Separators, maxsplit and Examples

Split a string in Python with str.split(). See split() vs split(‘ ‘), maxsplit, rsplit(), splitlines(), re.split() for several delimiters, and csv rows.

Python

The Python str.split() method breaks a string into a list of substrings, cutting at whitespace by default or at a separator we pass. Parsing a line of user input, a date such as 2026-10-09 or a simple comma-separated row all start with split().

colors = "red green  blue"
words = colors.split()            # ['red', 'green', 'blue']
parts = "2026-10-09".split("-")   # ['2026', '10', '09']

Below, we look at the difference between split() and split(” “), the maxsplit argument, rsplit() and splitlines(), and re.split() for several delimiters, with results from Python 3.14.

1. Syntax and Return Value

Both arguments are optional. The sep argument is the separator string, and maxsplit limits the number of cuts (the default -1 means no limit).

str.split(sep=None, maxsplit=-1) -> list[str]

The method returns a new list of strings and never changes the original string. With sep=None, it splits on any run of whitespace and drops empty strings, and with a given sep, it splits at every single occurrence and keeps the empty strings between neighbors.

2. split() vs split(” “)

Calling split() without arguments is not the same as split(” “). Most text has double spaces, tabs or a trailing newline, and only the no-argument form handles them.

line = "red  green\tblue\n"
by_whitespace = line.split()       # ['red', 'green', 'blue']
by_space = line.split(" ")         # ['red', '', 'green\tblue\n']
empty = "".split()                 # []
empty_sep = "".split(",")          # ['']

The last two lines matter when we parse optional fields. An empty string gives an empty list with the default separator, but a list with one empty string with an explicit separator.

3. Limiting Splits with maxsplit and rsplit()

When only the first part has a fixed meaning, maxsplit stops after a number of cuts and leaves the rest of the string intact. The rsplit() method does the same from the right, which splits off the last part of a dotted name. For real file paths, pathlib.Path(name).suffix also handles names without a dot.

setting = "path=/home/user=me"
key, value = setting.split("=", 1)            # 'path', '/home/user=me'
name, ext = "report.final.pdf".rsplit(".", 1) # 'report.final', 'pdf'

4. Splitting Lines with splitlines()

Text read from a file ends with a newline, so split(“\n”) leaves an empty string at the end and misses Windows line endings. The splitlines() method handles \n, \r\n and the other line boundaries.

text = "first\r\nsecond\n"
with_split = text.split("\n")      # ['first\r', 'second', '']
with_lines = text.splitlines()      # ['first', 'second']

5. Several Delimiters with re.split()

The split() method accepts one separator only. For a mix such as commas, semicolons and spaces, re.split() takes a regular expression.

import re

tags = "java, python;go   rust"
names = re.split(r"[,;\s]+", tags)           # ['java', 'python', 'go', 'rust']
with_seps = re.split(r"([,;])", "a,b;c")     # ['a', ',', 'b', ';', 'c']

A capture group in the pattern, the parentheses in the second call, keeps the delimiters in the result. We leave the group out unless we need them.

6. Which Method to Pick

The split() method is right for simple tokens, and partition() returns the part before a separator, the separator and the part after it as a tuple. Quoted CSV fields need the csv module, because a comma inside quotes is part of the value.

import csv

row = 'Lokesh,"Delhi, India",37'
naive = row.split(",")                   # ['Lokesh', '"Delhi', ' India"', '37']
fields = next(csv.reader([row]))         # ['Lokesh', 'Delhi, India', '37']
NeedUse
Words separated by any whitespaces.split()
One fixed separators.split(“,”)
Only the first or last cuts.split(sep, 1) or s.rsplit(sep, 1)
Lines of a texts.splitlines()
Head, separator and tail in one calls.partition(sep)
Several different delimitersre.split(pattern, s)
CSV rows with quotescsv.reader

7. Parsing key=value Lines into a Dictionary

Settings in a single line, such as host = db.local; port=5432, come as key=value pairs. The partition() method cuts at the first = only, which keeps any extra = in the value, and strip() removes the spaces around both parts.

raw = "host = db.local; port=5432; password=a=b"
settings = {}
for pair in raw.split(";"):
    key, _, value = pair.partition("=")
    settings[key.strip()] = value.strip()
# {'host': 'db.local', 'port': '5432', 'password': 'a=b'}

The values stay strings, so we convert numbers ourselves, for example int(settings[“port”]). For real query strings, urllib.parse.parse_qs() also decodes escaped characters such as %20.

8. Splitting Strings in Other Ways

Splitting into characters, numbers or fixed positions needs a different tool than split().

8.1. How do we split a string into characters?

The list() constructor returns one element per character, so list(“tea”) gives [‘t’, ‘e’, ‘a’]. The split() method cannot do it, because split(“”) raises ValueError: empty separator.

8.2. How do we split a string and convert the parts to numbers?

We combine split() with map() or a comprehension.

nums = list(map(int, "3 14 15".split()))      # [3, 14, 15]
floats = [float(p) for p in "1.5,2.25".split(",")]  # [1.5, 2.25]

8.3. How do we split a string at a position instead of a character?

Slicing does that, for example s[:3] and s[3:], because split() always looks for a separator.

9. Conclusion

For everyday parsing, split() without arguments handles messy whitespace, a separator argument handles fixed formats, and maxsplit or rsplit() keeps the rest of the string together. Lines go to splitlines(), mixed delimiters to re.split(), and quoted data to the csv module.

10. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.