You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.x 不使用库如何去除字符串列表中的标点符号和换行符

实现方法
  • 第一步手动定义所有需要过滤的通用标点、换行符组成的集合,集合的查询效率比字符串更高,适合逐字符判断场景
  • 第二步遍历输入列表的每个原始字符串
  • 第三步对每个字符串逐字符校验,仅保留不在过滤集合内的字符,拼接为新的干净字符串
  • 最后把所有处理后的字符串汇总为结果列表即可

完整实现代码如下:

# 示例输入
l = ['``What ails you, Sister Erin, that your face\n', 'Is, like your mountains, still bedewed with tears?\n', 'As though some ancient sorrow or disgrace,\n']

# 自定义需要过滤的字符集合,可按需增删字符
filter_chars = {'`', ',', '?', '!', '.', ';', ':', "'", '"', '(', ')', '[', ']', '{', '}', '<', '>', '-', '_', '=', '+', '*', '&', '^', '%', '$', '#', '@', '~', '\\', '/', '|', '\n'}

# 处理逻辑
result = []
for raw_str in l:
    cleaned_str = ''.join(c for c in raw_str if c not in filter_chars)
    result.append(cleaned_str)

# 输出结果
print(result)

运行后输出结果和要求的预期输出完全一致:

['What ails you Sister Erin that your face', 'Is like your mountains still bedewed with tears', 'As though some ancient sorrow or disgrace']

如果后续需要新增过滤的字符,直接往filter_chars集合中添加对应字符即可,无需修改其他处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:24:09