python:字符串split()方法
>>> str2 = '_'.join("FishC")>>> str2
'F_i_s_h_C'
>>> str2.split(sep='_')
['F', 'i', 's', 'h', 'C']
以上是小甲鱼python零基础书中P43的一段代码,留意这里加粗加背景色的部分。
而实际上这样写,运行后也是一样的效果:
>>> str2.split('_')
['F', 'i', 's', 'h', 'C']
两者有区别吗?
——————————————————
以下是我自己做练习打的代码,都没用到sep=
>>> str = 'I love this game!'
>>> str.split()
['I', 'love', 'this', 'game!']
>>> str.split('e', 1)
['I lov', ' this game!']
>>> str.split('e', 2)
['I lov', ' this gam', '!'] 不用写 sep,默认的 sep 是空格。sep 是 separator 的简写(分割符)
>>> str.split()
['I', 'love', 'this', 'game!']
如果说你把参数的顺序颠倒,那么要写 sep
str.split('e', 1) == str.split(1, sep='e')
本帖最后由 hhzczy 于 2018-10-19 09:08 编辑
claws0n 发表于 2018-10-19 00:00
不用写 sep,默认的 sep 是空格。sep 是 separator 的简写(分割符)
>>> str.split()
['I', 'love', 'th ...
似乎和你说的不一样哦,我刚刚试了一下:
>>> str = 'I love this game!'
>>> str.split('e', 2)
['I lov', ' this gam', '!']#正常
>>> str.split(sep='e')
['I lov', ' this gam', '!']#正常
>>> str.split(sep = 'e', 2)
SyntaxError: positional argument follows keyword argument
>>> str.split(2, sep='e')
Traceback (most recent call last):
File "<pyshell#232>", line 1, in <module>
str.split(2, sep='e')
TypeError: argument for split() given by name ('sep') and position (1) 是呢为啥呢 本帖最后由 wwhywhy 于 2018-10-20 08:58 编辑
1) str.split(sep='e', 2)
SyntaxError: positional argument follows keyword argument
2) str.split(sep='e', maxsplit=2)
['I lov', ' this gam', '!']
3) str.split(sep='e')
['I lov', ' this gam', '!']
所以如果要写参数,就要都写参数,不能只写一个。 wwhywhy 发表于 2018-10-20 08:54
1) str.split(sep='e', 2)
SyntaxError: positional argument follows keyword argument
2) str.split( ...
明白了,非常感谢。{:5_106:}
页:
[1]