【发布时间】:2021-11-19 10:41:57
【问题描述】:
我将 Markdown 文本存储在一个变量中,稍后我将其写入 MD 文件。 Markdown 包含尾随和前导空格以及只有空格的行。我试图从变量以及MD 文件中删除空格,但无济于事。
请注意:
- 标题 ## 包含前导空格
- 第 [1] 段包含前导空格
- 段落 [2] 之后的第二行不为空,但包含两个空格(可能在代码块中不可见)
- 段落 [a.] 后跟两个空格
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'))
【问题讨论】: