劈开一个哨子用了多少次

2024-04-24 07:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中使用split with a string,使用split语句中指定的分隔符将中的字符串转换为列表。你知道吗

如何确定在使用python拆分句子时使用了多少次split


Tags: 字符串列表stringwith语句句子split分隔符
2条回答

返回的list的长度减去1。你知道吗

>>> s = "this is a test string"
>>> s.split()
['this', 'is', 'a', 'test', 'string']
>>> len(s.split()) - 1
4

因此len(s.split()) - 1就是4,因为有4空间。你知道吗

s ="foo bar foobar"
print (s.split())
['foo', 'bar', 'foobar'] # three elements 
print len(s.split())-1  # get len of the list - 1, three elements but two splits

也可以将maxsplit参数传递给split

s ="foo bar foobar"
print (s.split(" ",2))  # split on first two

['foo', 'bar', 'foobar']

print(s.split(" ",1)) # split on first only
['foo', 'bar foobar']

相关问题 更多 >