课程
Python 字符串方法 split() 接收一个字符串值,默认以所有空白字符为分隔符,将字符串中的单词分开或拆分,并输出一个包含这些单词的列表。它还可以接收一个可选参数,用于限制拆分的次数。
split() 方法通过把字符串拆分成片段,将字符串转换为其他数据类型,例如 lists。Python 为我们提供了两种方法:.split() 和 .rsplit()。
.split() 和 .rsplit() 都接收一个用于拆分字符串的分隔元素,以及一个 maxsplit 参数,表示我们希望得到的子串最大数量。
使用 .split() 方法的示例

让我们使用 .split() 方法来拆分上面的字符串。请注意,.split() 方法从字符串的左侧开始拆分。它接收两个参数:分隔符 sep 和字符串的最大拆分次数 maxsplit。

将字符串拆分为多个子串的示例
在下面的示例中,您将把字符串 file 按行边界拆分为多个子串。接着,您将打印结果变量 file_split。最后,完成 for 循环,使用逗号作为分隔元素将字符串拆分为多个子串。

当我们运行上述代码时,会产生如下结果:
['mtv films election, a high school comedy, is a current example', 'from there, director steven spielberg wastes no time, taking us into the water on a midnight swim']
['mtv films election', ' a high school comedy', ' is a current example']
['from there', ' director steven spielberg wastes no time', ' taking us into the water on a midnight swim']。
想要了解更多字符串操作,请观看我们课程中的此视频:Python 正则表达式,并查看我们的 Python 正则表达式教程。
以上内容摘自 DataCamp 的 Python 正则表达式 课程,作者为 Maria Eugenia Inzaugarat。