How to use Python split()

What is the split() method?

The split() method splits a string into a list. Values in the list are separated using a separator character, mostly a whitespace by default.

Note: Common separators include whitespace and commas.

Syntax

The general syntax of the split() method is:

string_name.split(separator, maxsplit)
  1. separator is the character the split() function will use to separate the characters in the string. By default, it’s a whitespace and this parameter is optional.

  2. maxsplit is the maximum number of splits to be made. By default, it is equal to -1, which means that the function will split at all occurrences of the specified separator. This parameter is also optional.

Note: You do not need to import any libraries to use the split() function, since it’s a built-in function.

How does the split() function work?

Let’s split a sentence on a whitespace and see what we get!

sentence = "I am a split function"
split_sentence = sentence.split(" ")
print(split_sentence)

Let’s split a sentence on a comma , and see what we get!

sentence = "The shop has cats, dogs, hamsters, and turtles."
split_sentence = sentence.split(",")
print(split_sentence)

Now let’s set the maxsplit parameter as 2. Setting the maxsplit parameter to 2 will split the string two times on a #, and will return a list with three elements!

sentence = "I#am splitting on #hash#and#have#maxsplit#value of #2"
split_sentence = sentence.split("#", 2)
print(split_sentence)
Copyright ©2024 Educative, Inc. All rights reserved