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

Python 3中移除字符串非空行前导空格的技术求助

移除非空行前导空格的Python实现

需要处理字符串,移除所有非空行的前导空格,同时保留空行。当前输出与期望输出如下:

当前输出

Belgian Waffles
    $5.95
    Two of our famous Belgian Waffles with plenty of real maple syrup
    650


    Strawberry Belgian Waffles


    (extra output)


    Homestyle Breakfast
    $6.95
    Two eggs, bacon or sausage, toast, and our ever-popular hash browns
    950
(end of output)

期望输出

Belgian Waffles
$5.95
Two of our famous Belgian Waffles with plenty of real maple syrup
650


Strawberry Belgian Waffles


(extra output)


Homestyle Breakfast
$6.95
Two eggs, bacon or sausage, toast, and our ever-popular hash browns
950
(end of output)

修改后的完整代码

import os
import re


def get_filename():
    print("Enter the name of the file: ")
    filename = input()
    return filename


def read_file(filename):
    if os.path.exists(filename):
        with open(filename, "r") as file:
            full_text = file.read()
            return full_text
    else:
        print("This file does not exist")
    

def get_tags(full_text):
    tags = re.findall('<.*?>', full_text)
    for tag in tags:
        full_text = full_text.replace(tag, '')
    return tags


def get_text(text):
    # 移除HTML标签
    tags = re.findall('<.*?>', text)
    for tag in tags:
        text = text.replace(tag, '')
    # 拆分文本为行并处理前导空格
    lines = text.split('\n')
    processed_lines = []
    for line in lines:
        # 非空行移除所有前导空格,空行保持原样
        if line.strip():
            processed_lines.append(line.lstrip())
        else:
            processed_lines.append(line)
    # 合并处理后的行
    text = '\n'.join(processed_lines)
    # 移除文本首尾的空白字符
    text = text.strip()
    return text


def display_output(text):
    print(text)
    # 如果需要将结果转换为列表,取消下面两行注释
    # line_list = text.split('\n')
    # print(line_list)
    

def main():
    filename = get_filename()
    full_text = read_file(filename)
    if full_text is None:
        return
    tags = get_tags(full_text)
    text = get_text(full_text)

    display_output(text)


main()

关键处理逻辑说明

  1. 行拆分与处理:将文本按换行符拆分为行列表,遍历每行时,仅对非空行执行lstrip()操作移除所有前导空格,空行直接保留,确保格式不变。
  2. 列表转换:如果需要将处理后的字符串转为列表,只需调用text.split('\n'),即可得到每行元素组成的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:36:20