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.
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:
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"]
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:
split() Return Value
The split() method returns a list of strings.