PythonString methods
str. split()
Splits a string into a list of parts using a separator.
- Returns
- A list of strings.
- Changes the original
- No
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
csvmodule. A manualsplit(",")will not handle commas inside quotes. - Unpacking the result with
name, score = line.split(",")only works when there are exactly two parts.
Related entries
#- str.join()Joins the elements of a collection of strings into one string with a separator.
- str.splitlines()Splits a string into a list of lines.
- str.strip()Removes whitespace (or given characters) from the start and end of a string.
- list()Creates a list, either empty or from the items of another iterable.
Spotted a mistake or missing an example? Write to us.