48

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.

umbe1987
  • 2,894
  • 6
  • 35
  • 63

2 Answers2

92

You could use json.dumps()

>>> import json
>>> List = ["A", "B"]
>>> print json.dumps(List)
["A", "B"]
fn.
  • 2,788
  • 2
  • 27
  • 29
12

If you need the output formatted in a particular way, use something like 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.

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.

The interactive interpreter is essentially doing something like this each time you type in an expression (called, say, expr):

result = expr
if result is not None:
    print(repr(result))

Note that in my first example, print returns None, so the interpreter itself doesn't print anything. Meanwhile, the print function outputs the string itself, bypassing the logic above.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
  • Not sure that is a solution, considering if you remove the print call, it outputs `'"A"'` – Tim Sep 16 '15 at 11:03
  • Thanks, Anyway, I would need to avoid the use of the print function. Rather, I should work on the format of the list itself (if possible), to have the output of "List[0]" to be exactly "A" and not 'A'. – umbe1987 Sep 16 '15 at 11:05
  • 2
    @umbe1987 there is no difference between the two. It shows `'A'` because that is how the interpreter works, but under the hood they are the exact same string – Tim Sep 16 '15 at 11:06
  • 1
    @TimCastelijns Yes; that's because the interpreter calls `repr` on the result before displaying it. See my updated answer. – Will Vousden Sep 16 '15 at 11:11
  • 1
    @umbe1987 Lists don't have "output". If you want to output a variable with double quotes around it, you have to put them there yourself. What if you were using it with a different type of script that required back-ticks around strings instead? Python doesn't support that syntax, so you'd be stuck. – Will Vousden Sep 16 '15 at 11:13
  • Thanks to all. The problem was not a matter of double quotes indeed, rather a matter of switched variables in my list. The comment that 'A' and "A" is equal is therefore the answer to my problem. – umbe1987 Sep 16 '15 at 12:20