You need to enable JavaScript to run this app. Python中使用.replace()处理后部分字符串末尾为何留有空格?
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用.replace()处理后部分字符串末尾为何留有空格?

提取成绩为B的学生姓名时末尾留有空格的原因及解决办法

我正在从文本数据中提取特定信息,该数据包含学生姓名及对应成绩,格式示例如下:

Xxxxx Yyyyyy: B
Aaaaa Bbbbbb: A
Ccccc Dddddd: C
...
Mmmmm Nnnnnn: B

这是Coursera数据科学课程的任务,要求用Python提取成绩为B的学生姓名到列表中。我已经用正则完成了任务,现在尝试另一种方法,写了如下代码:

def grades():
    with open ("./grades.txt", "r") as file:
        grades = file.read()
    
    grades = grades.splitlines()
    matches = []
    for marks in grades:
        if ": B" in marks:
            matches.append(marks)
    matches = [match.replace(': B', '') for match in matches]
    return matches
print(grades())

代码运行后能得到结果,但部分学生姓名末尾留有空格,请问这是什么原因?

原因分析

问题出在你的文本数据格式上——有些行里的学生姓名和冒号之间多了一个空格,比如实际行可能是John Doe : B而不是John Doe: B。你用match.replace(': B', '')只会替换掉: B这部分,姓名后面的那个空格就被留在了字符串里,导致最终结果出现末尾空格。

解决办法

这里提供几种实用的修正方案:

方法1:分割后取姓名部分并去除空白

用split(':')把每行按冒号分割,取第一部分后用strip()去掉前后所有空白字符(包括空格、换行符等):

def grades():
    with open("./grades.txt", "r") as file:
        grades = file.read().splitlines()
    
    matches = []
    for line in grades:
        if ": B" in line:
            # 按冒号分割,取姓名部分并去除前后空白
            name = line.split(':')[0].strip()
            matches.append(name)
    return matches

方法2:反向分割后处理

从行的末尾反向分割一次,取前面的部分再用strip()清理:

def grades():
    with open("./grades.txt", "r") as file:
        grades = file.read().splitlines()
    
    matches = []
    for line in grades:
        if ": B" in line:
            # 从末尾分割一次,避免姓名里包含冒号的极端情况
            name = line.rsplit(': B', 1)[0].strip()
            matches.append(name)
    return matches

方法3:列表推导式简化

如果想让代码更简洁,直接用列表推导式完成所有逻辑:

def grades():
    with open("./grades.txt", "r") as file:
        return [line.split(':')[0].strip() for line in file if ": B" in line]

内容的提问来源于stack exchange,提问作者ckelmeckis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:01:50