Python String rsplit
Now, we are going to learn about the rsplit method. This method split’s the string from the right, on the specified separator, and it returns a list of the strings. If we are not providing the separator, then it defaults to whitespace. Let’s have a look at a simple program, which demonstrates the same thing.
Python String rsplit() Method
As you can see in the above program, we have a string, where we have different items. Then we are calling the rsplit method, and we have specified ‘, ‘ as the separator. So, the rsplit returns a list of strings, separated on the given separator. Let’s have a look at the output now.
[‘Sugar’, ‘Wheat’, ‘Rice’, ‘Butter’, ‘Cheese’]
As you can see in the output, we have a list of strings, separated at the given separator. If the separator is not specified, the separator is considered as the whitespace. Let’s have a look at another example, where we would not specify the separator as an argument to the rsplit method. Let’s have a look at the program.
As you can see in the above program, we have a string, and then we are calling the rsplit method on the string. Basically, we are not giving any separator here, so it would be considered as the whitespace. So, we get a list of strings, separated on the whitespace. Let’s have a look at the output now.
[‘Hello’, ‘from’, ‘GyaniPandit’]
As you can see in the output, we have the list of strings, separated at the whitespace. So, when we are not specifying the separator as an argument, it is considered as the whitespace.
Also, we can provide another optional argument, which is maxsplit, which specifies the number of times, the split’s are done. Let’s have a look at a simple program, which tries to demonstrate the same thing.
As you can see in the above program, we have a string, and then we are trying to call the rsplit method on the string. We have specified the separator, and this time, we also have specified the maxsplit argument, due to which, the split’s will be done 3 times. Let’s have a look at the output now.
[‘Sugar, Wheat’, ‘Rice’, ‘Butter’, ‘Cheese’]
As you can see in the output, we got a list of strings, and the splits were done 3 times. So, as and when required, we can make use of the rsplit method in our python programs. Remember that the rsplit method split’s the string on the specified separator, and it returns the list of strings.