Short Answer
if you're asking 'how to get it to work'.. then an easy solution would be to write a function that simply converts the list to a string.
if you run
print('\'' + r'\"quote\"' + '\'')
You will see
'\"quote\"'
Like you wanted. Now just need to apply this logic on a list. So it will be something like (I am using python 2.7.14 but I assume it is similar to your version):
def prettyPrintList(l):
print('[' + ','.join(map(lambda x: '\'' + x + '\'', l)) + ']')
prettyPrintList([r'\"quote\"'])
There's probably a nicer way to write it in python, I don't usually use python.
Long Answer
I would like to address the origin of the problem: "Why doesn't it just work?"
In OO languages - like python - when you print an object, like a list, it actually calls a function implicitly.
In python that function is str().
So technically you are running the code
print list.__str()__
That function defines the behavior that you see.
For lists, I assume it does something very similar to my "prettyPrint" function - It probably iterates over all the elements and calls .__str__()
on them, then joins them with a comma and wraps with brackets.
So in order to understand the output, lets have a look at .__str__()
when we call it directly on '\"quote\"'
>>> '\"quote\"'
'"quote"'
>>> '\"quote\"'.__str__()
'"quote"'
>>> r'\"quote\"'.__str__()
'\\"quote\\"'
>>>
As you can see, the REPL actually outputs the result of .__str__()
. So again, the result will be depended on that function's definition.
It seems to me that python chose a weird way to implement it.
If I do the same in JavaScript it yields different results between the browser and node (in console). In the browser it yields a similar result to what you desire
console.log(['\\"item\\"'])
> ["\"item\""]
And in the console
> console.log(['\\"quote\\"'])
[ '\\"quote\\"' ]
undefined
> console.log(['\"quote\"'])
[ '"quote"' ]
So as you can see it really depends on the implementation of the core function.
The best way you can guarantee things to be printed exactly like you need it, is to specify in code how you want to "stringify" it. basically, implement the function .__str__()
the way that suites you.
I hope I answered your question and convinced you about the solution.
If you have any more comments, please let me know