原文:Python split() – String Splitting Example,作者:Ihechikara Vincent Abba

Python 中的 split() 方法将字符串中的字符拆分为列表中的单独项目。

在本教程中,我们将介绍一些示例来帮助你学习如何使用 split() 方法。我们将从语法开始,然后看看如何修改使用 split() 方法的参数返回的列表。

Python 中 split() 方法的语法

split() 方法接受两个参数,语法如下所示:

str.split(separator, maxsplit)

上面的参数是 separatormaxsplit。这些参数都是可选的,但让我们讨论一下它们的作用。

separator 指定在什么字符处进行拆分。如果未指定,空格将用作发生拆分的默认字符。在接下来的示例中,你将更好地理解这一点。

maxsplit 指定最大拆分数,默认值为 -1,它允许连续的拆分次数。该参数也是可选的。

如何使用没有参数的 split() 方法

在本节中,我们将看到一些使用 split() 方法进行字符串拆分的示例,无需传入任何参数。

myString = "Python is a programming language"

print(myString.split())

# ['Python', 'is', 'a', 'programming', 'language']

在上面的代码中,我们创建了一个名为 myString 的字符串,该字符串由五个字符组成:“Python is a programming language”。

然后,我们使用点表示法对我们的字符串使用 split() 方法。

当打印到控制台时,字符串中的每个字符都成为列表数据类型中的一个单独项目:['Python', 'is', 'a', 'programming', 'language']

split() 方法能够分隔每个单词,因为默认情况下,空格表示每个字符的拆分点(请参阅上一节中的 separator 参数)。

如何使用带参数的 split() 方法

在本节中,我们将通过示例了解如何使用 split() 方法的参数。

myString = "Hello World!, if you're reading this, you're awesome"

print(myString.split(", "))

# ['Hello World!', "if you're reading this", "you're awesome"]

在上面的示例中,我们传入了一个逗号(,)作为 separator 分隔符:myString.split(", ")

因此,不是在每个空格之后拆分字符,而是仅在出现逗号时拆分字符:['Hello World!', "if you're reading this", "you're awesome"]。这意味着出现在逗号之前的字符将被组合在一起。

在下一个示例中,我们将使用第二个参数——maxsplit

myString = "Hello World!, if you're reading this, you're awesome"

print(myString.split(", ", 0))

# ["Hello World!, if you're reading this, you're awesome"]

我们在上面的代码中添加了 0 的 maxsplit 值,这控制了字符串的拆分方式。0 表示 1,因此字符作为列表中的一项返回:["Hello World!, if you're reading this, you're awesome"]

让我们更改数字,看看会发生什么。

myString = "Hello World!, if you're reading this, you're awesome"

print(myString.split(", ", 1))

# ['Hello World!', "if you're reading this, you're awesome"]

现在我们已将数字更改为 1,字符在列表中分为两个项目——“Hello World!” 和 “if you're reading this, you're awesome”。

默认情况下,省略 maxsplit 值会将其设置为 -1。这个负值允许 split() 方法将每个字符连续拆分为单独的项目,直到没有更多的字符。如果有指定的 separator,则将根​​据该值进行拆分——否则,将使用空格。

总结

在本文中,我们讨论了 Python 中的 split() 方法,该方法将字符串中的字符拆分并将它们作为列表中的项目返回。

我们看到了 split() 方法的语法和默认提供的两个参数——separatormaxsplit

我们还看到两个部分的示例。第一部分展示了如何使用没有参数的 split() 方法,而第二部分展示了我们如何使用该方法的参数来实现不同的结果。

祝你编程愉快!