使用双引号而不是单引号返回 Python 列表中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32606599/
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
Return a variable in a Python list with double quotes instead of single
提问by umbe1987
I am trying to return a variable from a list of strings in double quotes rather than single.
我试图从双引号而不是单引号中的字符串列表中返回一个变量。
For example, if my list is
例如,如果我的清单是
List = ["A", "B"]
if I type List[0]
the output is 'A'
. Rather, I want "A"
. Is there a way to do that? I need this because of an external script that runs in ArcGIS, which accepts only variables within double quotes.
如果我输入List[0]
输出是'A'
. 相反,我想要"A"
. 有没有办法做到这一点?我需要这个是因为在 ArcGIS 中运行的外部脚本只接受双引号内的变量。
回答by Will Vousden
If you need the output formatted in a particular way, use something like str.format()
:
如果您需要以特定方式格式化输出,请使用以下内容str.format()
:
>>> print('"{0}"'.format(List[0]))
"A"
The quotes you used to define the strings in the list are forgotten by Python as soon as the line is parsed. If you want to emit a string with quotes around it, you have to do it yourself.
一旦解析该行,Python 就会忘记用于定义列表中字符串的引号。如果你想发出一个带引号的字符串,你必须自己做。
What you're seeing is the Python interpreter displaying a string representation of the value of the expression. Specifically, if you type an expression into the interpreter that doesn't evaluate to None
, it will call repr
on the result in order to generate a string representation that it can display. For a string, this includes single quotes.
您看到的是 Python 解释器显示表达式值的字符串表示形式。具体来说,如果您在解释器中键入一个不计算为 的表达式None
,它将调用repr
结果以生成它可以显示的字符串表示。对于字符串,这包括单引号。
The interactive interpreter is essentially doing something like this each time you type in an expression (called, say, expr
):
每次输入表达式(例如,称为 )时,交互式解释器本质上都会执行以下操作expr
:
result = expr
if result is not None:
print(repr(result))
Note that my example, print
returns None
, so the interpreter itself doesn't print anything. Meanwhile, the print
function outputs the string itself, bypassing the logic above.
请注意,我的示例print
返回None
,因此解释器本身不打印任何内容。同时,该print
函数输出字符串本身,绕过上述逻辑。
回答by fn.
You could use json.dumps()
你可以使用json.dumps()
>>> import json
>>> List = ["A", "B"]
>>> print json.dumps(List)
["A", "B"]