Python:str.split() - 是否可以只指定 "limit"参数?

标签 python string

我想在空格(默认行为) 上拆分一个字符串,但我希望它只拆分一次 - 即我希望它返回一个最多包含 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/

相关文章:

ruby - 将字符串转换为 Ruby 中的条件

c - 如何将 char * 分配给字符数组?

python - 在 redshift UDF 中导入用户定义的库

python - 如何在分离模式下终止进程

Python:正则表达式在空格上分割(但在[]中保持元素不分割)并在数组中添加 ""作为换行符

将字符串数组的第一个单词与 c 中的字符串进行比较

java - 关于控制符号

python - 旋转标题和列

python - VSCode 没有选择 ipykernel

C++ 错误 : cannot convert ‘std::basic_string<char>’ to ‘const char*’