split() 与 rsplit()

问题描述 投票:0回答:1

我使用了

split()
rsplit()
,如下所示:

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

print(test.split("--")) # Here
print(test.rsplit("--")) # Here

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

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()

那么,

split()
rsplit()
有什么区别?

python python-3.x function split difference
1个回答
4
投票
  • split()可以从前面选择字符串中的位置进行分割。
  • rsplit()可以从后面选择字符串中的位置进行分割。
test = "1--2--3--4--5"

print(test.split("--", 2)) # Here
print(test.rsplit("--", 2)) # Here

输出:

['1', '2', '3--4--5'] # split()
['1--2--3', '4', '5'] # rsplit()

此外,如果

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

test = "1 2  3   4    5"

print(test.split()) # No arguments
print(test.rsplit()) # No arguments

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

['1', '2', '3', '4', '5'] # split()
['1', '2', '3', '4', '5'] # rsplit()

并且,只有

str
类型有
split()
rsplit()
,如下所示:

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

print(test.split()) # Error

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

test = True # Doesn't have rsplit()

print(test.rsplit()) # Error

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

© www.soinside.com 2019 - 2024. All rights reserved.