Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a variable in a Python list with double quotes instead of single

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.

like image 496
umbe1987 Avatar asked Sep 16 '15 10:09

umbe1987


People also ask

How do you replace single quotes with double quotes?

Use the String. replace() method to replace double with single quotes, e.g. const replaced = str. replace(/"/g, "'"); . The replace method will return a new string where all occurrences of double quotes are replaced with single quotes.

How do you print a double quote variable in Python?

Use a formatted string literal to add double quotes around a variable in Python, e.g. result = f'"{my_var}"' . Formatted string literals let us include variables inside of a string by prefixing the string with f . Copied!


2 Answers

You could use json.dumps()

>>> import json >>> List = ["A", "B"] >>> print json.dumps(List) ["A", "B"] 
like image 163
fn. Avatar answered Sep 29 '22 19:09

fn.


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 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.

like image 24
Will Vousden Avatar answered Sep 29 '22 20:09

Will Vousden