×


Python split() Function

The split() function is used to split a string and print out a list containing the words in that string. You can specify a separator between words in a string for the function to recognize.

In a short string, this command is very useful to split words and make it easier to parse the string.

Here at Ibmi Media, we shall look into how to use the split() function in Python through different examples.


More about the split() Function

The split() function will split a string into a list of words contained in the string.

You must specify a separator between words in a string for the function to recognize, the default is a space.

It's syntax is given below:

string.split(separator, maxsplit)

split() Function Parameter Values includes:

  • separator: delimiter.
  • maxsplit: number of parts you want to split.


Examples of using split() Function

1. Take a look at the below function:

str = "Welcome to my company"
x = str.split()
print(x)

It's Output is given below:

['Welcome', 'to', 'my', 'company']


2. separated by ",":

str = "Hello, my name is Linda, I'm 20 years old"
x = str.split(", ")
print(x)

It's Output is given below:

['Hello', 'my name is Linda', "I'm 20 years old"]


3. separated by "#":

str = "Hello#my name is Linda#I'm 20 years old"
x = str.split("#")
print(x)

The Output will give:

['Hello', 'my name is Linda', "I'm 20 years old"]


4. split into 2 parts:

str = "Hello#my name is Linda#I'm 20 years old"
x = str.split("#", 1)
print(x)

The Output will give:

['Hello', "my name is Linda#I'm 20 years old"]


[Need help in fixing Python function issues ? We can help you. ]


Conclusion

This article covers how to use the split() function in Python. In fact, The split() method breaks up a string at the specified separator and returns a list of strings.


split() Parameters

The split() method takes a maximum of 2 parameters:

  • separator (optional) - Delimiter at which splits occur. If not provided, the string is splitted at whitespaces.
  • maxsplit (optional) - Maximum number of splits. If not provided, there is no limit on the number of splits.


split() Return Value

The split() method returns a list of strings.