Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print empty string with double quotes instead of single quotes in Python

Tags:

python

string

I have a list I want to pretty print that contains empty lists as well as lists with string members. the problem is that lists that contains strings are printed with double quotes:

>>>str(['a'])
"['a']"

But an empty list is printed with single quotes:

>>> str([])
'[]'

Is there a way to always force printing string with double quotes ?

like image 249
iddober Avatar asked Jan 18 '26 01:01

iddober


2 Answers

It depends on the representation of the object being printed; if the string to print contains the \" character, then a single quote will be used; if the string contains the \' character, then a double quote will be used.

like image 94
Óscar López Avatar answered Jan 20 '26 16:01

Óscar López


Use custom string formatting:

print '"{}"'.format(str([]))

prints

"[]"

This won't affect strings nested in containers, though:

print '"{}"'.format(str(["a"]))

prints

"['a']"
like image 21
Sven Marnach Avatar answered Jan 20 '26 16:01

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!