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

0

When using these lines in the python terminal, I could not find a difference between any of them. I researched but I did not find anything about it, at least in Portuguese. What would be the difference between them?

x = 'apple, banana, cherry'
x.split(',')
x.rsplit(',')
    
asked by anonymous 01.12.2018 / 14:43

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 that:

In [2]: '1-2-3-4-5-6'.rsplit('-', maxsplit=3)
Out[2]: ['1-2-3', '4', '5', '6']
    
01.12.2018 / 15:11
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 the "signature" of rsplit accepts the parameter, max , that is, the maximum number of splits to be made, then the syntax is split(separador, max) , if max=-1 ( default) all possible splits will be made. Conclusion: If you use string.rsplit() without the max parameter, the result will be the same as string.split() .

    
01.12.2018 / 15:17