Sitelet https://www.datacamp.com/zh/tutorial/python-string-split
跳至内容

String Split in Python Tutorial

了解如何使用 Python 内置函数(如 split、join 和正则表达式)对字符串执行各种操作。
已更新 2026年10月6日  · 2分钟 阅读

使用 AI 探索

ChatGPTClaudePerplexity

Python 字符串方法 split() 接收一个字符串值,默认以所有空白字符为分隔符,将字符串中的单词分开或拆分,并输出一个包含这些单词的列表。它还可以接收一个可选参数,用于限制拆分的次数。

split() 方法通过把字符串拆分成片段,将字符串转换为其他数据类型,例如 lists。Python 为我们提供了两种方法:.split() 和 .rsplit()。

.split() 和 .rsplit() 都接收一个用于拆分字符串的分隔元素,以及一个 maxsplit 参数,表示我们希望得到的子串最大数量。

使用 .split() 方法的示例

string1

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

string2

将字符串拆分为多个子串的示例

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

substrings

当我们运行上述代码时,会产生如下结果:

['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。

主题
Python

进一步学习 Python

课程

Python 中的正则表达式

4 小时
49.9K
掌握字符串操作,精通正则表达式。
查看详情Right Arrow
开始课程
查看更多Right Arrow