Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a string with pyyaml without an ellipsis

I am trying to use yaml.dump with pyyaml to convert a string into something that is yaml safe (i.e., all things that need to be escaped are properly escaped). I will then insert these strings into a large yaml document.

The issue is that yaml.dump wants to treat the string as the whole document, and add ... (end of document), like

In [4]: yaml.dump("a string")
Out[4]: 'a string\n...\n'

How do I get it to not add the \n...\n, short of just manually removing it? Or is there a better way to quote a string for yaml consumption using pyyaml?

like image 536
asmeurer Avatar asked Feb 06 '15 23:02

asmeurer


1 Answers

Providing a default_style argument appears to help to some extent:

>>> yaml.dump("a string", default_style='"')
'"a string"\n'

There's also a line_break argument, but while it works for changing the terminating newline:

>>> yaml.dump("a string", default_style='"', line_break="\r")
'"a string"\r'

... it doesn't appear capable of removing it:

>>> yaml.dump("a string", default_style='"', line_break="")
'"a string"\n'
>>> yaml.dump("a string", default_style='"', line_break=None)
'"a string"\n'
>>> yaml.dump("a string", default_style='"', line_break=False)
'"a string"\n'
like image 64
Zero Piraeus Avatar answered Sep 20 '22 00:09

Zero Piraeus