有问题转义单引号 [英] Having issues escaping single quote

查看:43
本文介绍了有问题转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 ruamel.yaml 向 yaml 添加新值时,我很难转义单引号.

I'm having a hard time escaping single quotes when adding new values to yaml with ruamel.yaml.

下面是我在做的

import sys
from ruamel.yaml import YAML

yaml_doc = """\
Mappings:
  Values:
    '123': 'no'
"""

yaml = YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_doc)

new_value = data['Mappings']['Values']
new_value.insert(len(new_value), '456','' 'no'' ', comment="New Value")
new_value.insert(len(new_value), '789',' ''no' '', comment="New Value 2")
yaml.dump(data, sys.stdout)

使用此代码,对于我插入的值,我总是在 no 之后/之前得到一个前导或尾随空格.

With this code I always get a leading or trailing space after/before the no for the values I've inserted.

Mappings:
  Values:
    '123': 'no'
    '456': 'no '  # New Value
    '789': ' no' # New Value 2

如何插入带有单引号但没有尾随/标题空格的 no 值?

How can I insert the no value with single quotes but no trailing/heading space?

推荐答案

如果你想试试:

print(repr('' 'no'' '))

它会给你:

'no '

因为你所做的是将字符串 '' 与字符串 'no' 并置字符串 ' ',Python 只是在调用 print 之前将其连接到 'no '.你什么正在尝试做的是使用 YAML 单引号标量转义机制在 Python 中,只有当您 YAML().load() 来自 YAML 的字符串时,这才有效.

as what you do is juxtapose the string '' with the string 'no' and the string ' ', which Python just concatenates to 'no ' before calling print. What you are trying to do is use YAML single quotes scalar escaping mechanism in Python, and that would only work if you YAML().load() the string from YAML.

如果你想在你的输出中使用单引号标量,就像你有在您的输入中,您应该使标量与您得到的类型相同使用 .load().那是ruamel.yaml.scalarstring.SingleQuotedScalarString(作为 string子类).

If you want a single quoted scalar in your output, just like you have in your input, you should make scalar the same type as what you get using .load(). That is ruamel.yaml.scalarstring.SingleQuotedScalarString (as string subclass).

import sys
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString as sq

yaml_doc = """\
Mappings:
  Values:
    '123': 'no'
"""

yaml = YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_doc)

new_value = data['Mappings']['Values']
new_value['456'] = sq('no')
new_value.yaml_add_eol_comment(comment="New Value", key='456', column=0)
new_value.insert(len(new_value), '789', sq('no'), comment="New Value 2")
yaml.dump(data, sys.stdout)

这给出:

Mappings:
  Values:
    '123': 'no'
    '456': 'no' # New Value
    '789': 'no' # New Value 2

这篇关于有问题转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆