Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split() vs rsplit() in Python

Tags:

python

split

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()?

like image 841
Kai - Kazuya Ito Avatar asked Sep 11 '25 18:09

Kai - Kazuya Ito


1 Answers

  • 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()
like image 82
Kai - Kazuya Ito Avatar answered Sep 13 '25 08:09

Kai - Kazuya Ito