简体   繁体   English

Python3:如何使用print()打印带引号的字符串?

[英]Python3: How to use print() to print a string with quote?

I would like to ask, how to use print() in python3 to print the double quote (compulsory). 我想问一下,如何在python3中使用print()来打印双引号(强制)。

The code: 代码:

>>> List0 = ["1", "text", 25]
>>> print(List0)
['1', 'text', 25]
>>> str0 = str(List0)
>>> print(str0)
['1', 'text', 25]

str0 looks like a list but it is a string. str0看起来像一个列表,但它是一个字符串。 Using print() , the double quotes are not shown. 使用print() ,不显示双引号。 How to use the print() , but let the quotes shown? 如何使用print() ,但是让引号显示? It should be like: "['1', 'text', 25]" ? 它应该是: "['1', 'text', 25]"

Thanks for the help! 谢谢您的帮助!

It looks like you want to print what the string would look like if you were to assign it as a literal. 如果要将字符串指定为文字字符,看起来您想要打印字符串的样子。 For that, use repr , like this: 为此,使用repr ,如下所示:

print(repr(str0))

will print 将打印

"['1', 'text', 25]"

You can use the json module like so: 您可以像这样使用json模块:

import json

list0 = ["1", "text", 25]

print(json.dumps(list0)) #=> ["1", "text", 25]

Edit 编辑

To have double quotes on the outside use Python 3.6+ string interpolation: 要在外部使用双引号,请使用Python 3.6+字符串插值:

list0 = ["1", "text", 25]
print(f'"{list0}"')
"['1', 'text', 25]"

str.format does it all very simply: list to string conversion, formatting: str.format非常简单:list to string conversion,formatting:

>>> List0 = ["1", "text", 25]
>>> print('"{}"'.format(List0))
"['1', 'text', 25]"

You can escape from a string by using the character \\ : 您可以使用字符\\来转义字符串:

print("\"['1', 'text', 25]\"")  # "['1', 'text', 25]"

Alternatively you can use triple quotes: 或者,您可以使用三引号:

print('''"['1', 'text', 25]"''')  # "['1', 'text', 25]"

Print will not show quotes by default in a string. 默认情况下,打印不会在字符串中显示引号。 You will have to add them by concatenation. 您必须通过连接添加它们。

Print("\""+str0+"\"")

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

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