SoFunction
Updated on 2025-03-02

Analysis of the difference between split, rsplit, splitlines in Python

Python provides three methods of string segmentation:split()rsplit()andsplitlines();This article mainly introduces the differences between these three string segmentation functions through cases

1、split()

split()It is mainly used to match splitters from left to right. If no splitter is specified,split()Use whitespace as splitter

'''
 split(sep,maxsplit=-1)
 - sep: splitter
 - maxsplit: Find the first (segment times) matching split from left to right for splitting, default -1, split by all split characters
 '''
s = 'path/a/b/c'
print(('/'))                 # ['path', 'a', 'b', 'c']
print(('/', maxsplit=1))     # ['path', 'a/b/c']

2、rsplit()

rsplit()It is mainly used to match splitters from right to left. If no splitter is specified,rsplit()Use whitespace as splitter

'''
 rsplit(sep,maxsplit=-1)
 - sep: splitter
 - maxsplit: Find the first (segment times) matching split from right to left for splitting, default -1, split by all split characters
 '''
print(('/', maxsplit=1))    # ['path/a/b', 'c']

3、splitlines()

splitlines()Mainly used to split according to line breaks \r (carriage return), \r\n (carriage return and line break), \n (line break)

s = 'path\ra\r\nb\nc'
print(())               # ['path', 'a', 'b', 'c']

This is the end of this article about the differences between split(), rsplit(), and splitlines() in Python. For more information about the differences between split(), rsplit(), and splitlines() in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!