📜  python split() 源代码 - Python (1)

📅  最后修改于: 2023-12-03 15:19:00.928000             🧑  作者: Mango

Python split()源代码

简介

Python的split()方法是用于指定分隔符对字符串进行拆分的方法。源代码中包含该方法的实现,可以让我们更深入地了解这个常用的字符串处理函数。

源代码
def split(self, sep=None, maxsplit=-1):
    """
    Return a list of the words in the string, using sep as the delimiter string.

    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

    Splits are done starting at the beginning of the string and working
    towards the end, unless the optional argument maxsplit is specified 
    and nonzero, in which case splits are done from the end of the string
    backwards.
    """
    if sep is None:
        sep = ' '
    if not isinstance(sep, basestring):
        raise TypeError("expected a string separator")
    start = 0
    lst = []
    while True:
        # getting separator position
        idx = self.find(sep, start)
        if idx == -1:
            break
        lst.append(self[start:idx])
        start = idx + len(sep)
        # check number of splits
        if maxsplit > -1 and len(lst) == maxsplit:
            break
    lst.append(self[start:])
    return lst
用法

split()方法返回一个由拆分后的字符串组成的列表。可以传入分隔符参数sep,也可以不传入。

默认情况下,当不传入sep时,split()会根据任何空格符(空格、制表符、换行符等)对字符串进行拆分,并且会丢弃拆分后出现的空字符串。

当传入sep时,split()会根据sep参数对字符串进行拆分。如果传入了maxsplit参数,则只会拆分出前maxsplit个字符串。

示例代码如下:

sentence = "This is a sentence."
words = sentence.split()
print(words)
# Output: ['This', 'is', 'a', 'sentence.']

sentence = "This is a sentence."
words = sentence.split(' ')
print(words)
# Output: ['This', 'is', 'a', 'sentence.']

sentence = "This is a sentence."
words = sentence.split(' ', 2)
print(words)
# Output: ['This', 'is', 'a sentence.']
总结

Python split()方法是一种字符串处理常用的函数,通过将源代码展示出来,我们可以进一步了解该函数的实现原理以及使用方法。同时,此代码片段的注释也为我们提供了解释和指导。