Python 2.X在字符串周围添加单引号

pyC*_*hon 9 python python-2.7

目前要在字符串周围添加单引号,我提出的最佳解决方案是创建一个小包装函数.

def foo(s1):
    return "'" + s1 + "'"
Run Code Online (Sandbox Code Playgroud)

这样做有更简单的pythonic方式吗?

Kry*_*ton 15

关于什么:

def foo(s1):
    return "'%s'" % s1
Run Code Online (Sandbox Code Playgroud)

  • @Rico:这显然是一个答案.如有疑问,请不要复习.绝对不要只为自己的缘故发布cookie cut评论. (6认同)

Ósc*_*pez 13

这是另一个(也许更pythonic)选项,使用格式字符串:

def foo(s1):
    return "'{}'".format(s1)
Run Code Online (Sandbox Code Playgroud)


alc*_*emy 10

只是想强调@metatoaster在上面的评论中所说的内容,因为我一开始就错过了它.

使用repr(string)将添加单引号,然后在其之外加双引号,然后在带有转义内部单引号的单引号之外,然后转到其他转义.

除非存在其他冲突,否则使用repr()作为内置函数更直接.

s = 'strOrVar'
print s, repr(s), repr(repr(s)), ' ', repr(repr(repr(s))), repr(repr(repr(repr(s))))

# prints: strOrVar 'strOrVar' "'strOrVar'"   '"\'strOrVar\'"' '\'"\\\'strOrVar\\\'"\''
Run Code Online (Sandbox Code Playgroud)

文档说明其基本状态再版(),即表示,是EVAL的反向():

"对于许多类型,此函数尝试返回一个字符串,该字符串在传递给eval()时会产生具有相同值的对象,"

反引用会更短,但在Python 3+ 中删除.有趣的是,StackOverflow使用反引号来指定代码跨度,而不是突出显示代码块并单击代码按钮 - 但它有一些有趣的行为.