python字符串拆分

    科技2025-03-28  8

    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. Conclusion9. 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 docs

    — 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("-",maxsplit=2))#Output:['red', 'orange', 'yellow-purple']

    示例5:如果字符串中不存在sep(分隔符),则不会拆分字符串-它将返回包含字符串本身的列表 (Example 5: If a sep (delimiter) isn’t present in the string, it won’t split the string — it’ll return a list containing the string itself)

    s="HelloPython"print (s.split())#Output:['HelloPython']

    示例6:sep(分隔符)也可以包含多个字符-它们被分组在一起 (Example 6: A sep (delimiter) can contain multiple characters also — they’re grouped together)

    colors="red<>green<>yellow<>blue<orange"print(colors.split("<>"))#Output:['red', 'green', 'yellow', 'blue<orange']

    rsplit() (rsplit())

    “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, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right,rsplit()behaves like split().”

    “使用sep作为分隔符字符串,返回字符串中的单词列表。 如果给出了maxsplit,则最多完成maxsplit拆分,最右边的拆分完成。 如果未指定sep或None ,则任何空格字符串都是分隔符。 除了从右侧拆分外,rsplit()的行为类似于split()。”

    — Python docs

    — Python文档

    str.rsplit(sep=None,maxsplit=-1)

    str.rsplit(sep=None,maxsplit=-1)

    Return type → List

    返回类型→清单

    示例1:如果未提及sep(分隔符),它将根据字符串中的空格拆分字符串-仅与split()相同(Example 1: If no sep (delimiter) is mentioned, it’ll split the string based on the whitespaces in the string — same as split() only)

    a="Hello Python"print (a.rsplit())#Output:['Hello', 'Python']

    示例2:如果将maxsplit提到为1,它将在第一个出现在右边的位置分裂; 如果将maxsplit设为2,则它将在右边的前两次出现时进行拆分 (Example 2: If a maxsplit is mentioned as 1, it’ll split on the first occurrence from the right; if a maxsplit is given as 2, it’ll split on the first two occurrences from the right)

    colors="red-orange-yellow-purple"print (colors.rsplit("-",maxsplit=1))#Output:['red-orange-yellow', 'purple']print (colors.rsplit("-",maxsplit=2))#Output:['red-orange', 'yellow', 'purple']

    splitlines() (splitlines())

    “Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.”

    “返回字符串中的行列表,在行边界处中断。 除非给出了正确的保留符,否则换行符不会包含在结果列表中。”

    — Python docs

    — Python文档

    str.splitlines([keepends])

    str. splitlines ([ keepends ])

    示例1:根据换行符分割字符串 (Example 1: Splitting the string based on line breaks)

    colors="red\norange\nyellow\npurple"print (colors.splitlines())#Output:['red', 'orange', 'yellow', 'purple']

    示例2:通过提及keepends = True包含换行符 (Example 2: Line breaks are included by mentioning keepends=True)

    colors="red\norange\nyellow\npurple"print (colors.splitlines(keepends=True))#Output:['red\n', 'orange\n', 'yellow\n', 'purple']

    示例3:split()vs splitlines() (Example 3: split() vs splitlines())

    colors="red\norange\nyellow\npurple\n"print (colors.splitlines())#Output:['red', 'orange', 'yellow', 'purple']print(colors.split("\n"))#Output:['red', 'orange', 'yellow', 'purple', '']

    划分() (partition())

    “Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.”

    “在第一次出现sep时分割字符串,并返回一个三元组,其中包含分隔符之前的部分,分隔符本身以及分隔符之后的部分。 如果找不到分隔符,则返回一个包含字符串本身的三元组,然后是两个空字符串。”

    — Python docs

    — Python文档

    str.partition(sep)

    str.partition(sep)

    Return type → Tuple

    返回类型→元组

    示例1:在第一次出现sep(定界符)时分割字符串(Example 1: Splits the string at the first occurrence of a sep (delimiter))

    colors="red-orange-yellow-purple"print (colors.partition("-"))#Output:('red', '-', 'orange-yellow-purple')

    示例2:sep用作空格 (Example 2: The sep is given as a space)

    s="Hello Python"print (s.partition(" "))#Output:('Hello', ' ', 'Python')

    示例3:如果未提及Sep,则将引发TypeError (Example 3: If a sep isn’t mentioned, it’ll raise a TypeError)

    s="Hello Python"print (s.partition())#Output:TypeError: partition() takes exactly one argument (0 given)

    示例4:如果在字符串中未找到sep,它将返回一个包含字符串本身的3元组,然后是两个空字符串 (Example 4: If a sep isn’t found in the string, it’ll return a 3-tuple containing the string itself, followed by two empty strings)

    s="HelloPython"print (s.partition(" "))#Output:('HelloPython', '', '')

    rpartition() (rpartition())

    “Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.”

    “在最后一次出现sep时分割字符串,并返回一个三元组,其中包含分隔符之前的部分,分隔符本身以及分隔符之后的部分。 如果找不到分隔符,则返回一个包含两个空字符串的三元组,然后是字符串本身。”

    — Python docs

    — Python文档

    str.rpartition(sep)

    str.rpartition(sep)

    示例1:在最后一次出现sep(定界符)时分割字符串 (Example 1: Splits the string at the last occurrence of a sep (delimiter))

    colors="red-orange-yellow-purple"print (colors.rpartition("-"))#Output:('red-orange-yellow', '-', 'purple')

    示例2:如果在字符串中未找到sep,则返回一个三元组,其中包含两个空字符串,然后是字符串本身 (Example 2: If a sep isn’t found in the string, a 3-tuple will return containing two empty strings, followed by the string itself)

    s="HelloPython"print (s.rpartition(" "))#Output:('', '', 'HelloPython')

    示例3:如果未提及Sep,则将引发TypeError (Example 3: If a sep isn’t mentioned, it’ll raise a TypeError)

    s="Hello Python"print (s.rpartition())#Output:TypeError: rpartition() takes exactly one argument (0 given)

    re.split() (re.split())

    “Split string by the occurrences of pattern. If capturing parentheses are used in the pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.”

    “通过模式的出现来分割字符串。 如果模式中使用了捕获括号,那么模式中所有组的文本也将作为结果列表的一部分返回。 如果maxsplit不为零,则最多会发生maxsplit分割,并将字符串的其余部分作为列表的最后一个元素返回。”

    — Python docs

    — Python文档

    re.split(pattern, string, maxsplit=0, flags=0)

    re. split ( pattern , string , maxsplit=0 , flags=0 )

    Return type → List

    返回类型→清单

    示例1:通过使用空格作为分隔符来分割字符串(Example 1: Splitting the string by giving a space as a delimiter)

    s="Hello Python"import reprint (re.split(" ",s))#Output:['Hello', 'Python']

    示例2:使用单个定界符分割字符串 (Example 2:Splitting the string with a single delimiter)

    colors="red-orange-yellow-purple"import reprint (re.split("-",colors))#Output:['red', 'orange', 'yellow', 'purple']

    示例3:使用re.split分割带有多个定界符的字符串 (Example 3: Spitting the string with multiple delimiters using re.split)

    re.split(‘[&$-]’,colors

    re.split('[&$-]',colors

    [&$-] → []is used to indicate a set of characters. Multiple delimiters are given within the square bracket. re.split() will split the string if any of the delimiters mentioned are found.

    [&$-] → []用于指示一组字符。 方括号内给出了多个定界符。 如果找到任何提到的分隔符, re.split()将分割字符串。

    colors="red&orange-yellow$purple"import reprint (re.split('[&$-]',colors))#Output:['red', 'orange', 'yellow', 'purple']

    示例4:在出现字母数字(az,AZ,0-9)和下划线以外的任何其他字符时拆分字符串 (Example 4: Splitting the string at the occurrences of any character other than alphanumerics (a-z, A-Z, 0–9) and underscore)

    re.split(‘\W’,colors)

    re.split('\W',colors)

    \W → Matches all characters except a-z, A-Z, and 0-9

    \W →匹配除az,AZ和0-9以外的所有字符

    colors="red%yellow,blue!orange@purple"import reprint (re.split('\W',colors))#Output:['red', 'yellow', 'blue', 'orange', 'purple']

    示例5:在出现数字以外的任何字符时分割字符串 (Example 5: Splitting the string at the occurrence of any character other than numbers)

    re.split(‘\D’,num)

    re.split('\D',num)

    \D → Matches all characters except 0-9

    \D →匹配除0-9以外的所有字符

    num="1,2%3&4!5@6"import reprint (re.split('\D',num))#Output:['1', '2', '3', '4', '5', '6']

    示例6:给出了最大分裂 (Example 6: A maxsplit is given)

    If a maxsplit is mentioned as 1, it’ll split on the first occurrence only. If a maxsplit is given as 2, it’ll split on the first two occurrences only.

    如果将maxsplit提到为1 ,则它将仅在第一次出现时进行拆分。 如果将maxsplit为2 ,则它将仅在前两次出现时进行拆分。

    colors="red-orange-yellow-purple"import reprint (re.split("-",colors,maxsplit=1))#Output:['red', 'orange-yellow-purple']print (re.split("-",colors,maxsplit=2))#Output:['red', 'orange', 'yellow-purple']

    split()和partition()之间的区别 (Differences Between split() and partition())

    Image source: author 图片来源:作者

    结论(Conclusion)

    str.split() → It’ll split the string by each occurrence of the delimiter (sep)

    str.split() →它将根据每次出现的定界符(sep)来分割字符串

    str.partition() → It’ll split the string on the first occurrences of the delimiter (sep)

    str.partition() →它将在第一次出现分隔符时分隔字符串(sep)

    str.rpartition() → It’ll split the string on the last occurrences

    str.rpartition() →它将在最后一次出现时拆分字符串

    of the delimiter (sep)

    分隔符(9月)

    re.split() → It’ll split the string on the occurrences of the pattern. Multiple delimiters can be used to split the string.

    re.split() →它将在模式出现时拆分字符串。 多个定界符可用于拆分字符串。

    资源(Python文档) (Resources (Python Documentation))

    str.split

    str.split

    str.rsplit

    str.rsplit

    str.splitlines

    str.splitlines

    str.rpartition

    str.rpartition

    re.split

    re.split

    翻译自: https://medium.com/better-programming/split-vs-partition-in-python-strings-9505d070af55

    python字符串拆分

    Processed: 0.010, SQL: 8