What is the difference between string.split(',') and string.rsplit(',') in python?

Asked

Viewed 1,297 times

0

Using these lines in the python terminal, I couldn’t find any difference between them. I searched but found nothing about, at least in Portuguese. What would be the difference between them ?

x = 'apple, banana, cherry'
x.split(',')
x.rsplit(',')

2 answers

2


The difference appears when passing the optional argument maxsplit. It determines the maximum number of divisions to be made.

In the case of split, the algorithm starts from the left and the elements at the beginning of the list are divided:

In [1]: '1-2-3-4-5-6'.split('-', maxsplit=3)
Out[1]: ['1', '2', '3', '4-5-6']

In the case of rsplit, the algorithm starts from the right (from the end of the string) and the last occurrences are:

In [2]: '1-2-3-4-5-6'.rsplit('-', maxsplit=3)
Out[2]: ['1-2-3', '4', '5', '6']

1

See these examples

text = 'Essa, é, uma, string, de, teste' 
rs1 = text.rsplit(',',1)

rs1
['Essa, é, uma, string, de', ' teste']


rs2 = text.rsplit(',',2)

rs2
['Essa, é, uma, string', ' de', ' teste']

rs_1 = text.rsplit(',',-1)

rs_1
['Essa', ' é', ' uma', ' string', ' de', ' teste']

The difference between split and rsplit is that rsplit’s "signature" accepts the parameter , max, i.e., the maximum number of splits to be done, so the syntax is split(separador, max), if max=-1 (default) all possible splits will be done. Conclusion: If you use string.rsplit() without the parameter max, the result will be the same as string.split().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.