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)
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.split()
method returns a list of substrings obtained after splitting the original string.Here are some examples to illustrate how the split()
method works:
text = "Hello, this is a sample string"
words = text.split()
print(words)
# Output: ['Hello,', 'this', 'is', 'a', 'sample', 'string']
csv_data = "John,Doe,30,New York"
fields = csv_data.split(',')
print(fields)
# Output: ['John', 'Doe', '30', 'New York']
maxsplit
text = "apple orange banana cherry"
fruits = text.split(maxsplit=2)
print(fruits)
# Output: ['apple', 'orange', 'banana cherry']
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.