如何连接 Python 中的单个引号

How to concatenate individual quote marks in Python

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

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

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

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

像这样:

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

但是,我只能通过输入带有双引号和单引号的 bar arg 来使其工作,如下所示:"'bar'".

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

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

编辑:我找到了一种方法:

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

有没有更优雅的方案?

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

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

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

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

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

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

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