String split() Method in Python

Python String split() Method

The split() method in Python is used to split a string into a list of substrings based on a specified delimiter. The method is available for all string objects and has the following syntax:

str.split(separator, maxsplit)

Parameters:

  • separator (optional): This is the delimiter on which the string will be split. If not provided, the method splits the string at whitespace characters (spaces, tabs, newlines).
  • maxsplit (optional): This parameter specifies the maximum number of splits to perform. If provided, the method will split the string at most maxsplit number of times. The remaining part of the string will be left as it is. If maxsplit is not given or set to -1, then there is no limit on the number of splits.

Return value:

  • The split() method returns a list of substrings obtained after splitting the original string.

Here are some examples to illustrate how the split() method works:

Using the default separator (whitespace characters)

text = "Hello, this is a sample string"
words = text.split()
print(words)
# Output: ['Hello,', 'this', 'is', 'a', 'sample', 'string']

Splitting on a specific character

csv_data = "John,Doe,30,New York"
fields = csv_data.split(',')
print(fields)
# Output: ['John', 'Doe', '30', 'New York']

Using maxsplit

text = "apple orange banana cherry"
fruits = text.split(maxsplit=2)
print(fruits)
# Output: ['apple', 'orange', 'banana cherry']

Splitting on a multi-character separator

text = "The:quick:brown:fox"
parts = text.split(':')
print(parts)
# Output: ['The', 'quick', 'brown', 'fox']

Keep in mind that if the separator is not found in the string, the split() method will return a list with a single element, which is the original string. For example:

text = "Just a single word"
result = text.split(':')
print(result)
# Output: ['Just a single word']

In this case, since there is no : in the string, the entire string is returned as a single-element list.