如何在保留空行的同时从 MD 文件的每一行中删除前导和尾随空格?

How to remove leading and trailing whitespace from each line in an MD file while preserving empty lines?

我将 Markdown 文本存储在一个变量中,稍后我将其写入 MD 文件。 Markdown 包含尾随和前导空格以及仅包含空格的行。我试图从变量和 MD 文件中删除空格,但无济于事。

请注意:

markdown = ''' ## This is a headline

 [1] This is the first paragraph

[2] This is the second paragraph

  
a. This is the third paragraph;  
b. This is the fourth paragraph.'''

with open("output.md", "w") as f_out:
    f_out.write(markdown)

理想情况下,output.md 应该是这样的:

## This is a headline

[1] This is the first paragraph

[2] This is the second paragraph

a. This is the third paragraph;
b. This is the fourth paragraph.

编辑:将@Mortz 接受的答案应用于真实来源,我意识到 Markdown 使用两个空格作为 <br> 标签。因此在这种情况下不需要删除尾随空格。可以删除前导空格:clean_markdown = '\n'.join(_.lstrip() for _ in markdown.split('\n'))

您可以在换行符处拆分 - '\n' 并重新加入所有条目,去除前导和尾随空格 -

print(repr(markdown))
#' ## This is a headline\n\n [1] This is the first paragraph\n \n [2] This is the second paragraph\n \n   \n   a. This is the third paragraph;  \n   b. This is the fourth paragraph.'

clean_markdown = '\n'.join(_.strip() for _ in markdown.split('\n'))

print(repr(clean_markdown))
#'## This is a headline\n\n[1] This is the first paragraph\n\n[2] This is the second paragraph\n\n\na. This is the third paragraph;\nb. This is the fourth paragraph.'

并将此 clean_markdown 写入您的文件