Multiline Yaml Strings

Published on Aug. 23, 2022 | Tags: yaml TIL

If you want to have a multiline string in a YAML file you can use the > syntax:


---
multiline_string: >
line1
line2
line3

will produce:
multiline_string: line1 line2 line3


However, if we have a very long string we want to break into multiple lines but no spaces, we have to escape the newlines instead:


---
multiline_string: "line1\
line2\
line3"

which will produce:


multiline_string: line1line2line3

Complete example:


import yaml

raw_yaml = """
---
multiline_string: >-4
line1
line2
line3
multiline_string_2: "line1\
line2\
line3"
"""
print(yaml.dump(yaml.load(raw_yaml, yaml.Loader)), end="")

Ref: https://stackoverflow.com/questions/53098493/how-to-nicely-split-on-multiple-lines-long-conditionals-with-or-on-ansible


Ferran Jovell