我想在空格(默认行为) 上拆分一个字符串,但我希望它只拆分一次 - 即我希望它返回一个最多包含 2 个项目的数组。
如果不可能 - 即如果为了指定限制我还必须指定模式 - 你能告诉我如何指定默认模式吗?
最佳答案
这个有效:
>>> 'a b c'.split(None, 1)
['a', 'b c']
文档字符串:
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
您应该在交互式提示下探索:
>>> help('a'.split)
在 IPython 中只需使用问号:
In [1]: s = 'a'
In [2]: s.split?
我建议使用 IPython尤其是笔记本。这使得这种探索更加方便。
关于Python:str.split() - 是否可以只指定 "limit"参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30437566/