Python YAML 保留换行符而不添加额外的换行符

Python YAML preserving newline without adding extra newline

我有一个与 this question 类似的问题,我需要在 YAML 映射值字符串中插入换行符并且不想自己插入 \n。答案建议使用:

Data: |
      Some data, here and a special character like ':'
      Another line of data on a separate line

而不是

Data: "Some data, here and a special character like ':'\n
      Another line of data on a separate line"

它还在末尾添加了一个换行符,这是不可接受的。

我尝试使用 Data: >,但结果显示完全不同。在阅读 yaml 文件后,我一直在剥离最后的换行符,这当然有效,但并不优雅。有没有更好的方法来保留换行符 而无需在末尾添加额外的换行符 ?

我正在使用 python 2.7 fwiw

如果您使用 | 这会使标量变为 literal block style scalar。但是 | 的默认行为是剪裁,这不会让你得到你想要的字符串(因为它留下了最后的换行符)。

您可以通过附加 block chomping indicators

"modify" | 的行为

Strip

Stripping is specified by the “-” chomping indicator. In this case, the final line break and any trailing empty lines are excluded from the scalar’s content.

Clip

Clipping is the default behavior used if no explicit chomping indicator is specified. In this case, the final line break character is preserved in the scalar’s content. However, any trailing empty lines are excluded from the scalar’s content.

Keep

Keeping is specified by the “+” chomping indicator. In this case, the final line break and any trailing empty lines are considered to be part of the scalar’s content. These additional lines are not subject to folding.

通过将 stripchomping 运算符“-”添加到“|”,您可以 prevent/strip 最后的换行符:¹

import ruamel.yaml as yaml

yaml_str = """\
Data: |-
      Some data, here and a special character like ':'
      Another line of data on a separate line
"""

data = yaml.load(yaml_str)
print(data)

给出:

{'Data': "Some data, here and a special character like ':'\nAnother line of data on a separate line"}


¹ 这是使用 ruamel.yaml 完成的,我是作者。使用 PyYAML(其中 ruamel.yaml 是一个超集,在往返过程中保留注释和文字标量块)应该会得到相同的结果。