Home > OS >  split() vs rsplit() in Python
split() vs rsplit() in Python

Time:12-13

I used split() and rsplit() as shown below:

test = "1--2--3--4--5"

print(test.split("--")) # Here
print(test.rsplit("--")) # Here

Then, I got the same result as shown below:

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()

So, what's the difference between split() and rsplit()?

CodePudding user response:

  • split() can select the position in a string from the front to divide.
  • rsplit() can select the position in a string from the back to divide.
test = "1--2--3--4--5"

print(test.split("--", 2)) # Here
print(test.rsplit("--", 2)) # Here

Output:

['1', '2', '3--4--5'] # split()
['1--2--3', '4', '5'] # rsplit()

In addition, if split() and rsplit() have no arguments as shown below:

test = "1 2  3   4    5"

print(test.split()) # No arguments
print(test.rsplit()) # No arguments

They can divide a string by one or more spaces as shown below:

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()

And, only str type has split() and rsplit() as shown below:

test = ["12345"] # Doesn't have split()

print(test.split())

AttributeError: 'list' object has no attribute 'split'

test = True # Doesn't have rsplit()

print(test.rsplit()) 

AttributeError: 'bool' object has no attribute 'rsplit'

CodePudding user response:

The split() method splits a string into a list of substrings based on a specified delimiter. The rsplit() method is similar to split(), but it splits the string starting from the right side, rather than the left. This means that the substrings in the resulting list will be in reverse order, with the last substring appearing first in the list.

Here is an example to illustrate the difference:

test = "1-2-3-4-5"

# Split the string using the '-' delimiter, starting from the left
result = test.split("-")
print(result)  # Output: ['1', '2', '3', '4', '5']

# Split the string using the '-' delimiter, starting from the right
result = test.rsplit("-")
print(result)  # Output: ['5', '4', '3', '2', '1']

In the first call to split(), the string is split into substrings using the '-' delimiter, starting from the left side of the string. This results in a list of substrings in the order they appear in the original string. In the second call to rsplit(), the string is split starting from the right side, so the resulting list of substrings is in reverse order.

  • Related