str.split()

Splits a string into a list of parts using a separator.

Returns
A list of strings.
Changes the original
No
On this page

Example

#
Python
sentence = "Learning  Python   daily"
print(sentence.split())

csv_line = "Emma,92,,HTML"
print(csv_line.split(","))

setting = "theme=dark=mode"
print(setting.split("=", 1))
Resultsaved result, you can check it
['Learning', 'Python', 'daily']
['Emma', '92', '', 'HTML']
['theme', 'dark=mode']

Definition and usage

#

The split() method splits a string into a list of fragments. Without an argument, it splits on any whitespace and skips empty fragments, so several spaces in a row do not create empty elements.

With an argument, it splits exactly where the separator occurs, for example a comma. Then two separators next to each other produce an empty string in the result.

The maxsplit parameter limits the number of splits, which is handy for data like "key=value=with=characters". The opposite of split() is join().

Syntax

#
Syntax
string.split(sep=None, maxsplit=-1)

Parameters

#
  • sep

    str, optional

    The separator. Defaults to any whitespace.
  • maxsplit

    int, default -1

    The maximum number of splits. -1 means no limit.

Good practices

#
  • For CSV files, use the csv module. A manual split(",") will not handle commas inside quotes.
  • Unpacking the result with name, score = line.split(",") only works when there are exactly two parts.

Related entries

#

Spotted a mistake or missing an example? Write to us.