Python string rsplit() method
Python String rsplit() Method
Description
The rsplit() method returns a list of all the words in a string, using sep as the delimiter (if not specified, splits on all whitespace characters), optionally limiting the number of splits to num. If num is given, the string is split starting from the right. If num is not specified, the behavior is the same as split().
Syntax
The syntax of the rsplit() method is as follows:
var.rsplit(sep, num))
Parameters
- sep – This is any delimiter character, defaults to space.
- num – This is the number of strings to generate.
Return Value
This method returns a list of strings.
Example
The following example shows the usage of the rsplit() method.
var = 'Explicit is better than implicit'
var1 = var.rsplit()
print ("Original string:", var)
print ("Result of rsplit:", var1)
var = "911-7342-058"
var2 = var.rsplit('-')
print ("Original string:", var)
print ("Result of rsplit:", var2)
var = 'Explicit is better than implicit'
var3 = var.rsplit(' ',2)
print ("Original string:", var)
print ("Result of rsplit:", var3)
When you run this program, the following output is produced −
Original string: Explicit is better than implicit
rsplit Result: ['Explicit', 'is', 'better', 'than', 'implicit']
Original string: 911-7342-058
Result of rsplit: ['911', '7342', '058']
Original string: Explicit is better than implicit
Result of rsplit: ['Explicit is better', 'than', 'implicit']