Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python YAML preserving newline without adding extra newline

Tags:

python

yaml

I have a similar problem to this question that I need to insert newlines in a YAML mapping value string and prefer not to insert \n myself. The answer suggests using:

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

instead of

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

which also adds a newline at the end, that is unacceptable.

I tried using Data: > but that showed to give completely different results. I have been stripping the final newline after reading in the yaml file, and of course that works but that is not elegant. Any better way to preserve newlines without adding an extra one at the end?

I am using python 2.7 fwiw

like image 972
Arthur Avatar asked Jun 24 '15 09:06

Arthur


1 Answers

If you use | This makes a scalar into a literal block style scalar. But the default behaviour of |, is clipping and that doesn't get you the string you wanted (as that leaves the final newline).

You can "modify" the behaviour of | by attaching block chomping indicators

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.

By adding the stripchomping operator '-' to '|', you can prevent/strip the final newline:¹

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)

gives:

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


¹ This was done using ruamel.yaml of which I am the author. You should get the same result with PyYAML (of which ruamel.yaml is a superset, preserving comments and literal scalar blocks on round-trip).

like image 171
Anthon Avatar answered Nov 15 '22 08:11

Anthon