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

2024-06-14 01:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

def foo(s1):
    return "'" + s1 + "'"

有没有更简单的方法来做这件事?


Tags: 方法函数字符串returnfoodef解决方案小包装
3条回答

只是想强调一下@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\\\'"\''

docs状态的基本状态repr(),即表示,与eval()相反:

"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(),.."

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

下面是另一个(可能更像Python)选项,使用format strings

def foo(s1):
    return "'{}'".format(s1)

怎么办:

def foo(s1):
    return "'%s'" % s1

相关问题 更多 >