简体   繁体   English

在Python中使用双引号而不是单引号打印空字符串

[英]Print empty string with double quotes instead of single quotes in Python

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']) >>> STR([ '一'])
"['a']" “['一个']”

But an empty list is printed with single quotes: 但是一个空列表用单引号打印:

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

Is there a way to always force printing string with double quotes ? 有没有办法总是用双引号强制打印字符串?

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. 如果要打印的字符串包含\\"字符,则将使用单引号;如果字符串包含\\'字符,则将使用双引号。

Use custom string formatting: 使用自定义字符串格式

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

prints 版画

"[]"

This won't affect strings nested in containers, though: 但这不会影响嵌套在容器中的字符串:

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

prints 版画

"['a']"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM