Python String split() Method With Example

Python String split

Now, we are going to learn about the split method. This split method split’s the string at the given separator, and then returns a list of strings. If we do not specify the separator, the string is split on the whitespaces. Let’s have a look at a simple program, which tries to demonstrate the same thing.

Python String split() Method

As you can see in the above program, we have a simple string, and then we are calling the split method. We also have specified the separator here, and the method is going to return the list of strings. Let’s have a look at the output now.

[‘Sugar’, ‘Wheat’, ‘Rice’, ‘Butter’, ‘Cheese’]

As you can see in the output, we have the string splitted at the given separator, and the method returned a list of the strings.

Also, we can specify another argument, which is maxsplit, which simply specifies that at most maxsplit splits are done. Let’s have a look at the program now, which tries to demonstrate the same thing.

As you can see in the above program, we have a simple string, and then we are calling the split method. This time, we have specified the maxsplit argument as well. If you have a look at the output of the above program, we can find that the splits are done three times. Let’s have a look at the output now.

[‘Sugar’, ‘Wheat’, ‘Rice’, ‘Butter, Cheese’]

As you can see in the output, we have got the list of strings, and the splits were done three times as specified in the argument. So, as and when required, we can specify the maxsplit argument.

Now, the thing is that if we do not specify the separator, it defaults to whitespace.

Let’s have a look at a simple program, which specifies the same thing.

As you can see in the above program, we have a string, and then we are calling the split method. This time, we have not specified any separator, so it would be splitted on the whitespaces. Let’s have a look at the output now, which would make a clear picture in your mind, about the output from the program.

[‘Hello’, ‘from’, ‘GyaniPandit’]

As you can see, we have got a list of strings, which is splitted over the whitespaces.

So, as and when required, we can make use of the split method, which split’s our string at the given separator, and returns the list of strings. We can also provide an optional argument, which is the maxsplit. If we do not specify the separator, it defaults to whitespaces.