python字符串拆分
split()与partition()(split() vs. partition())
In Python, we can split the string by using the following methods. Let’s look at these methods in detail.
在Python中,我们可以使用以下方法拆分字符串。 让我们详细看看这些方法。
1. split()
2. rsplit()
3. splitlines()
4. partition()
5. rpartition()
6. re.split()
7. Differences between split() and partition()
8. Conclusion
9. Resources
分裂() (split())
“Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most
maxsplit+1
elements). If maxsplit is not specified or-1
, then there is no limit on the number of splits (all possible splits are made).”“使用sep作为分隔符字符串,返回字符串中的单词列表。 如果指定了maxsplit,则最多完成maxsplit个分割(因此,列表最多包含
maxsplit+1
元素)。 如果未指定maxsplit或-1
,则分割数没有限制(已进行所有可能的分割)。”— Python文档
str.split(sep=None,maxsplit=-1)
str.split(sep=None,maxsplit=-1)
Return type → List
返回类型→清单
示例1:如果未提及sep
(分隔符),它将根据字符串中的空格将字符串拆分(Example 1: If a sep
(delimiter) isn’t mentioned, it’ll split the string based on the whitespaces in the string)
a="Hello Python"print (a.split())
#Output:['Hello', 'Python']
示例2:如果提到了sep(分隔符),它将根据分隔符的出现进行拆分 (Example 2: If a sep (delimiter) is mentioned, it’ll split based on the occurrences of the delimiter)
colors='red-green-blue-yellow'print (colors.split("-"))
#Output:['red', 'green', 'blue', 'yellow']
例子3 (Example 3)
a="three times by three makes nine"print (a.split(sep="three"))
#Output:['', ' times by ', ' makes nine']
示例4:提到最大拆分 (Example 4: A maxsplit is mentioned)
If maxsplit
is mentioned as 1
, it’ll split on the first occurrence only.If maxsplit
is given as 2
, it’ll split on the first two occurrences only.
如果将maxsplit
称为1
,则仅在第一次出现时拆分;如果将maxsplit
设为2
,则仅在前两个出现时拆分。
colors="red-orange-yellow-purple"print (colors.split("-",maxsplit=1))
#Output:['red', 'orange-yellow-purple']print (colors.split(&#