【问题标题】:How to concatenate individual quote marks in Python如何在 Python 中连接单个引号
【发布时间】:2015-09-20 09:14:42
【问题描述】:

我正在尝试将 lxml 方法合并到我正在构建的另一个函数中。

lxml 将一个用双引号括起来的字符串作为输入。在该字符串中包含另一个用单引号括起来的术语。像这样:

root.findall(".//*[@name='File Name']")

但是,我想从函数的参数中传递单引号 ('File Name') 中的值。

像这样:

def foo(bar):
    root.findall(".//*[@name="+bar+"]")

但是,我只能通过输入带有双引号和单引号的 bar 参数来使其工作,例如:"'bar'"

如何配置,只需要写'bar'

我试过+"\""+bar+"\""+,但没用。

编辑:我想出了一种方法:

def foo(bar):
    atr = '"'+atr+'"'
    root.findall(".//*[@name="+bar+"]")

有没有更优雅的解决方案?

【问题讨论】:

    标签: python string python-2.7 lxml quotes


    【解决方案1】:

    有点不清楚你在问什么。我想这就是你想要的:

    def foo(bar):
        root.findall(".//*[@name='{}']".format(bar))
    

    这意味着如果您调用foo("XYZ"),它将调用root.findall(".//*[@name='XYZ']")

    【讨论】:

    • 你的意思是{}而不是%s
    • 呵呵,还在想printf-mode。
    • 就是这样。谢谢!
    【解决方案2】:

    也许您可以更改 foo() 函数以在 lxml findall() 函数调用中包含单引号,例如 -

    def foo(bar):
        root.findall(".//*[@name='" + bar + "']")
    

    如果您想转义单引号,可以使用 \' 来实现。示例 -

    >>> '\'bar\''
    "'bar'"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多