ZetCode

Python 分割字符串

最后修改于 2024 年 1 月 29 日

Python 分割字符串教程展示了如何在 Python 中分割字符串。

我们可以使用以下方法在 Python 中分割字符串

Python split/rsplit 方法

split 方法根据给定的分隔符参数将字符串切割成多个部分。 使用可选的第二个参数,我们可以控制字符串被切割的次数。

str.split([sep[, maxsplit]])

str.split 方法返回字符串中的单词列表,这些单词由分隔符字符串分隔。

参数如下:


   
str.rsplit([sep[, maxsplit]])

str.rsplit 返回字符串中的单词列表,这些单词由分隔符字符串分隔(从右侧开始)。

Python 分割示例

在以下示例中,我们使用前面提到的方法将字符串切割成多个部分。

splitting.py
#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.split(',')
print(words)

words2 = line.split(', ')
print(words2)

words3 = line.split(',')
words4 = [e.strip() for e in words3]
print(words4)

在该示例中,我们将用逗号分隔的一行单词切割成一个单词列表。

words = line.split(',')

字符串由逗号字符切割;但是,单词中包含空格。

words2 = line.split(', ')

消除空格的一种方法是在分隔符参数中包含空格字符。

words3 = line.split(',')
words4 = [e.strip() for e in words3]

另一种解决方案是使用 strip 方法。

$ ./splitting.py 
['sky', ' club', ' cpu', ' cloud', ' war', ' pot', ' rock', ' water']
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

使用 maxsplit 参数,我们可以设置将要完成的分割次数。

maxsplit.py
#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.split(', ', 3)

for word in words:
    print(word)

print('-------------------------')

words2 = line.split(', ', 4)

for word in words2:
    print(word)

剩余的单词构成一个字符串。

$ ./maxsplit.py
sky
club
cpu
cloud, war, pot, rock, water
-------------------------
sky
club
cpu
cloud
war, pot, rock, water

在下一个示例中,我们从字符串的末尾获取单词。

split_right.py
#!/usr/bin/python

line = "sky, club, cpu, cloud, war, pot, rock, water"

words = line.rsplit(', ', 3)[-3:]
print(words)

使用 rsplit 方法,我们获得最后三个单词。

$ ./split_right.py 
['pot', 'rock', 'water']

Python splitlines

str.splitlines 方法返回字符串中的行列表,在行边界处断开。除非将 keepends 设置为 True,否则行分隔符不会包含在结果列表中。

行边界是包括换行符 \n、回车符 \r 和回车/换行符 \r\n 在内的字符。

str.splitlines([keepends])

这是一种将文件中的行快速分割成列表的便捷方法。

split_lines.py
#!/usr/bin/python

line = "sky\nclub\ncpu\rcloud\r\nwar\npot\nrock\nwater"

words = line.splitlines()
print(words)

该示例将字符串转换为单词列表。

$ ./split_lines.py
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

在下一个示例中,我们从文件中读取单词。

words.txt
sky
cup
blue
bear
rock
pen
chair
lamp
bowl
rock
falcon

我们有一个单词文件。

split_lines2.py
#!/usr/bin/python

filename = 'words.txt'

with open(filename, 'r') as f:
    
    data = f.read()
    words = data.splitlines()
    
    print(words)

read 方法将整个文件读取到字符串中。然后使用 split_lines 将字符串分割成行。

$ ./split_lines2.py 
['sky', 'cup', 'blue', 'bear', 'rock', 'pen', 'chair', 'lamp', 'bowl', 'rock', 'falcon']

Python re.split

使用 re.split,我们可以使用正则表达式分割字符串。

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

该方法为我们提供了更强大的选项来切割字符串。

reg_split.py
#!/usr/bin/python

import re

line = "sky, \nclub, \tcpu; cloud,  \n\n\nwar; pot, rock, water"

words = re.split("[;,]\s+", line)
print(words)

在该示例中,我们使用 re.spit 将字符串分割成单词列表。单词可以用逗号或分号以及多个空格分隔。

$  ./reg_split.py 
['sky', 'club', 'cpu', 'cloud', 'war', 'pot', 'rock', 'water']

Python 单词频率

在以下示例中,我们计算单词频率。

$ wget https://raw.githubusercontent.com/janbodnar/data/main/the-king-james-bible.txt

我们使用《英王钦定本圣经》。

word_freq.py
#!/usr/bin/python

import collections
import re

filename = 'the-king-james-bible.txt'

def get_words():

    words = []

    with open(filename) as f:

        for line in f:

            fields = re.split("\W+", line)

            for w in fields:

                if w and not w.isdigit():
                    words.append(w)

    return words

words = get_words()

c = collections.Counter(words)
common = c.most_common(10)

for e, i in common:
    print(f'{e}: {i}')

该示例打印来自 the-king-james-bible.txt 文件中的十个最常见的单词。

fields = re.split("\W+", line)

我们将该行分割成单词。 \W 字符类匹配任何非单词字符的字符。

for w in fields:

if w and not w.isdigit():
     words.append(w)

我们跳过空字段和诗句注释(它们包含数字)。

c = collections.Counter(words)
common = c.most_common(10)

我们计算出现次数并打印前十个频繁单词。

$ ./word_freq.py 
the: 62103
and: 38848
of: 34478
to: 13400
And: 12846
that: 12576
in: 12331
shall: 9760
he: 9665
unto: 8942

Python 字符串 partition

partition 方法在给定分隔符的第一次出现处分割序列,并返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。

rpartition 方法在给定分隔符的最后一次出现处分割序列,并返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。

partition.py
#!/usr/bin/python

import os 

files = os.listdir('.')

for file in files:
    
    data = file.partition('.')
    print(f'{data[0]} has extension {data[2]}')

该示例列出当前工作目录并将每个文件切割成其名称和扩展名。它使用 partition

$ ./partition.py 
words has extension txt
split_lines2 has extension py
splitting has extension py
split_lines has extension py
word_freq2 has extension py
split_right has extension py
the-king-james-bible has extension txt
reg_split has extension py
word_freq has extension py
partition has extension py
maxsplit has extension py

来源

Python 语言参考

在本文中,我们展示了如何在 Python 中分割字符串。

作者

我叫 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 Python 教程