你想用Python把一个字符串变成一个字符串的数组吗?一种方法是用Python内置的.split() 方法来实现。
这里有一个如何在Python命令行中做到这一点的例子:
>>> string1 = "test your might"
>>> string1.split(" ");
# Output: ['test', 'your', 'might']
你可以从你的命令行中打开Python REPL。Python内置于Linux、Mac和Windows中。我写了一份指南,介绍如何从 Mac 终端打开最新版本的 Python。
注意,上面的例子中的", "参数实际上是可选的,看看这个吧:
>>> string1 = "test your might"
>>> string1.split();
# Output: ['test', 'your', 'might']
>>> string2 = "test,your,might"
>>> s.split();
# Output: ['test', 'your', 'might']
Python.split() 方法足够聪明,可以推断出分隔符应该是什么。在string1 中,我使用了一个空格。在string2 中,我使用了一个逗号。在这两种情况下,它都起作用了。
如何使用Python .split()和一个特定的分隔符
在实践中,你会想传递一个separator 作为参数。让我告诉你如何做到这一点:
>>> s = "test your might"
>>> s.split(" ");
# Output: ['test', 'your', 'might']
>>> s2 = "test,your,might"
>>> s.split(",");
# Output: ['test', 'your', 'might']
输出结果是一样的,但它更干净。下面是一个更复杂的字符串,指定分隔符会产生更大的不同:
>>> string3 = "excellent, test your might, fight, mortal kombat"
>>> string3.split(",");
# Output: ['excellent', ' test your might', ' fight', ' mortal kombat']
>>> string3.split(" ");
# Output: ['excellent,', 'test', 'your', 'might,', 'fight,', 'mortal', 'kombat']
正如你所看到的,指定一个分隔符是比较安全的做法。
还要注意的是,前导和尾部的空格可能会包含在你的数组中的一些字符串中。这只是需要注意的问题。
在 Python 中如何将一个字符串分割成多个字符串?
你可以把一个字符串分割成你需要的许多部分。这完全取决于你想在什么字符上分割字符串。
但是如果你想确保一个字符串不会被分割成超过一定数量的部分,你将想在你的函数调用中使用传递maxsplit 参数。
如何在Python中把一个字符串分成3部分?
如果你想给你的字符串被分割成的部分数量设定一个上限,你可以使用maxsplit 参数来指定,像这样:
string3 = "excellent, test your might, fight, mortal kombat"
print(string.split(" ", 3))
# Output: ['excellent,', 'test', 'your', 'might, fight, mortal kombat']
# maxsplit=3 means that string will be split into at most three parts
正如你所看到的,split 函数只是在第3个空格后停止了对字符串的分割,所以在结果数组中总共有4个字符串。