本文介绍了我可以控制多行字符串的格式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

from ruamel.yaml import YAML
import sys, textwrap

yaml = YAML()
yaml.default_flow_style = False
yaml.dump({
    'hello.py': textwrap.dedent("""\
        import sys
        sys.stdout.write("hello world")
    """)
}, sys.stdout)

产生:

hello.py: "import sys\nsys.stdout.write(\"hello world\")\n"

有没有办法让它产生:

hello.py: |
    import sys
    sys.stdout.write("hello world")

相反?

版本:

python: 2.7.16 on Win10 (1903)
ruamel.ordereddict==0.4.14
ruamel.yaml==0.16.0
ruamel.yaml.clib==0.1.0

推荐答案

如果加载然后转储预期输出,您将看到ruamel.yaml可以实际保留块样式的文字标量.

If you load, then dump, your expected output, you'll see that ruamel.yaml can actuallypreserve the block style literal scalar.

import sys
import ruamel.yaml

yaml_str = """\
hello.py: |
    import sys
    sys.stdout.write("hello world")
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)

因为这再次提供了已加载的输入:

as this gives again the loaded input:

hello.py: |
  import sys
  sys.stdout.write("hello world")

要了解如何检查多行字符串的类型,请执行以下操作:

To find out how it does that you should inspect the type of your multi-line string:

print(type(data['hello.py']))

打印:

<class 'ruamel.yaml.scalarstring.LiteralScalarString'>

这应该为您指明正确的方向:

and that should point you in the right direction:

from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import LiteralScalarString
import sys, textwrap

def LS(s):
    return LiteralScalarString(textwrap.dedent(s))


yaml = ruamel.yaml.YAML()
yaml.dump({
    'hello.py': LS("""\
        import sys
        sys.stdout.write("hello world")
    """)
}, sys.stdout)

它还会输出您想要的内容:

which also outputs what you want:

hello.py: |
  import sys
  sys.stdout.write("hello world")

这篇关于我可以控制多行字符串的格式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:00