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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22952543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:02:40  来源:igfitidea点击:

Python 2.X adding single quotes around a string

pythonpython-2.7

提问by pyCthon

Currently to add single quotes around a string, the best solution I came up with was to make a small wrapper function.

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

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

Is there an easier more pythonic way of doing this?

有没有更简单的 Pythonic 方法来做到这一点?

回答by óscar López

Here's another (perhaps more pythonic) option, using format strings:

这是使用格式字符串的另一个(可能更pythonic)选项:

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

回答by Krypton

What about:

关于什么:

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

回答by alchemy

Just wanted to highlight what @metatoaster said in the comment above, as I missed it at first.

只是想强调@metatoaster 在上面的评论中所说的话,因为我一开始错过了。

Using repr(string) will add single quotes, then double quotes outside of that, then single quotes outside of that with escaped inner single quotes, then onto other escaping.

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

Using repr(), as a built-in, is more direct, unless there are other conflicts..

使用 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\\'"\''

The docsstate its basically state repr(), i.e. representation, is the reverse of eval():

文档说明其基本状态再版(),即表示,是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(),.."

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

Backquotes would be shorter, but are removedin Python 3+. Interestingly, StackOverflow uses backquotes to specify code spans, instead of highlighting a code block and clicking the code button - it has some interesting behavior though.

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