如何移除Python字符串中所有不以指定字符开头的部分?
移除Python字符串中所有不以指定字符开头的内容
根据你的场景,分几种常见情况给出实现代码:
情况1:多行文本,保留以'5'开头的行
如果你的字符串是多行格式,只需筛选出以'5'开头的行即可:
# 示例输入文本 raw_text = """52019 report Q3 sales summary 52020 report annual review 52021 forecast""" # 按行分割后筛选,再重新拼接 filtered_lines = [line for line in raw_text.split('\n') if line.startswith('5')] cleaned_text = '\n'.join(filtered_lines) print(cleaned_text)
输出结果:
52019 report 52020 report 52021 forecast
情况2:单行文本,提取所有以'5'开头的子串
如果是单行文本,需要提取所有以'5'开头的连续字符序列(比如空格分隔的单词),可以用正则表达式实现:
import re raw_text = "5apple banana 5orange grape 5pear" # 匹配所有以5开头、后续非空白的字符序列 cleaned_text = ' '.join(re.findall(r'5\S+', raw_text)) print(cleaned_text)
输出结果:
5apple 5orange 5pear
自定义分隔符场景
如果你的文本用其他分隔符(比如逗号、分号),只需调整分割逻辑:
raw_text = "5a, b, 5c, d, 5e" filtered_items = [item.strip() for item in raw_text.split(',') if item.strip().startswith('5')] cleaned_text = ', '.join(filtered_items) print(cleaned_text) # 输出:5a, 5c, 5e
内容的提问来源于stack exchange,提问作者user22190930
相关产品推荐
相关产品推荐

