Rt Rtt
Rt Rtt

Reputation: 617

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

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. Using print(), the double quotes are not shown. How to use the print(), but let the quotes shown? It should be like: "['1', 'text', 25]" ?

Thanks for the help!

Upvotes: 7

Views: 3769

Answers (5)

Cyzanfar
Cyzanfar

Reputation: 7146

You can use the json module like so:

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:

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

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140297

str.format does it all very simply: list to string conversion, formatting:

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

Upvotes: 2

cco
cco

Reputation: 6301

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:

print(repr(str0))

will print

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

Upvotes: 15

Rinkesh Golwala
Rinkesh Golwala

Reputation: 1049

Print will not show quotes by default in a string. You will have to add them by concatenation.

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

Upvotes: 0

Alex
Alex

Reputation: 19124

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]"

Upvotes: 0

Related Questions