Python: Split String

By Xah Lee. Date: .

Split String

str.split(?sep, ?maxSplit)
Split string using sep as the delimiter. Return a list.

If sep is None, split by consecutive whitespaces, with leading or trailing whitespace removed.

print(" a   b  c ".split() == ["a", "b", "c"])

empty string return empty list.

print("".split() == [])

maxSplit is max count of split. (result length is at most maxSplit+1).

print("a b c d".split(" ", 2) == ["a", "b", "c d"])

If sep is given, it is taken as literal, not regex.

print("1,,2".split(",") == ["1", "", "2"])

sep can be multiple chars.

print("1,,2".split(",,") == ["1", "2"])

Splitting an empty string with a specified separator returns [''].

print("".split(",") == [""])
str.rsplit(?sep, ?maxsplit)
Same as split but begin at right.
str.splitlines(?keepends)
Return a list of the lines in the string, breaking at line boundaries.

This method uses the universal newlines approach to splitting lines.

Line breaks are not included in the resulting list unless keepends is given and true.

xx = "ab c\n\nde fg\rkl\r\n"

print(xx.splitlines() == ["ab c", "", "de fg", "kl"])

print(xx.splitlines(True) == ["ab c\n", "\n", "de fg\r", "kl\r\n"])

Empty string returns empty list

print("".splitlines() == [])
str.partition(sep)
Split the string at the first occurrence of sep, and return a 3-Tuple containing the part before the separator, the separator itself, and the part after the separator.

If the separator is not found, return (str, "", "")

str.rpartition(sep)
Same as partition but begin at right.

Python, String