Python 中的 split() 与 rsplit()

4 python split function python-3.x difference

我用的split()是and,rsplit()如下图:

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

print(test.split("--")) # Here
print(test.rsplit("--")) # Here
Run Code Online (Sandbox Code Playgroud)

然后,我得到了相同的结果,如下所示:

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()
Run Code Online (Sandbox Code Playgroud)

split()那么,和 之间有什么区别rsplit()

小智 6

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

print(test.split("--", 2)) # Here
print(test.rsplit("--", 2)) # Here
Run Code Online (Sandbox Code Playgroud)

输出:

['1', '2', '3--4--5'] # split()
['1--2--3', '4', '5'] # rsplit()
Run Code Online (Sandbox Code Playgroud)

另外,如果split()rsplit()没有参数,如下所示:

test = "1 2  3   4    5"

print(test.split()) # No arguments
print(test.rsplit()) # No arguments
Run Code Online (Sandbox Code Playgroud)

他们可以将字符串除以一个或多个空格,如下所示:

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()
Run Code Online (Sandbox Code Playgroud)

并且,只有str类型有split()and,rsplit()如下所示:

test = ["1 2 3 4 5"] # Doesn't have split()

print(test.split()) # Error
Run Code Online (Sandbox Code Playgroud)

AttributeError:'list'对象没有属性'split'

test = True # Doesn't have rsplit()

print(test.rsplit()) # Error
Run Code Online (Sandbox Code Playgroud)

AttributeError:“bool”对象没有属性“rsplit”