Mattreex
Mattreex

Reputation: 199

How do I prevent new line \ characters from being output to YAML when I use ruamel.yaml.scalarstring.DoubleQuotedScalarString?

I am attempting to write a python dictionary to a yaml file using ruamel.yaml. I need some strings to be explicitly quoted so I pass them to ruamel.yaml.scalarstring.DoubleQuotedScalarString which wraps them in double quotes in output. However, strings that are covered over multiple lines contain \ characters in them in the output. How do I prevent this?

I tried searching for \ with regex after I pass the string to the ruamel.yaml.scalarstring.DoubleQuotedScalarString and replace them with '' but this does not work. I think these characters are added at the time of dumping.

S = ruamel.yaml.scalarstring.DoubleQuotedScalarString
string = "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."
st = S(string)
data = {'key': st}

f = open('./yam.yaml', 'w')
yaml= YAML()
yaml.default_flow_style = False
yaml.indent(offset = 2, sequence = 4, mapping = 2)
yaml.dump(data, f)

Expected:

key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."

Actual:

key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise\
  \ and quantify the various aspects of nocturnal sleep problems in Parkinson's disease\
  \ (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."

Upvotes: 1

Views: 1386

Answers (1)

Anthon
Anthon

Reputation: 76599

What you see is caused by the line wrapping, that tries to limit the line length to the default of 80 characters, in the output.

If you can live with wider output, then just set yaml.width to a larger value:

import sys
import ruamel.yaml
YAML = ruamel.yaml.YAML

S = ruamel.yaml.scalarstring.DoubleQuotedScalarString
string = "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."
st = S(string)
data = {'key': st}

yaml= YAML()
yaml.width = 2048
yaml.default_flow_style = False
yaml.indent(offset = 2, sequence = 4, mapping = 2)
yaml.dump(data, sys.stdout)

which gives:

key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."

Upvotes: 2

Related Questions