yaml.safe_load removes whitespaces if also contains a line break

27 Views Asked by At

I'm working with the library PyYAML==6.0.1 and trying to retrieve an object from a string representation of a YAML.

The problem is, when I use yaml.safe_load with a text containing a line break then it removes the whitespaces.

For example:

data = yaml.safe_load("first\n\n         second")

returns a string with the linebreak but the whitespaces removed

'first\nsecond'

If I don't add the line break then the whitespaces are kept.

How can I keep both things (the linebreak and the whitespace)?

1

There are 1 best solutions below

0
mbanchero On BEST ANSWER

With the help of @KamilCuk I finally checked the official YAML documentation and found a solution for my problem.

My solution was to add a literal scalar into my YAML representation string, and remove the second '\n' because it was not longer needed (see literal style docs):

yaml.safe_load("|-\n first\n         second")

This way the result of the previous operation is:

'first\n         second'