Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add double quotes to string in python

Tags:

python

string

If my input text is

a
b
c
d
e
f
g

and I want my output text to be: (with the double quotes)

"a b c d e f g"

Where do I go after this step:

" ".join([a.strip() for a in b.split("\n") if a])
like image 959
qwertylpc Avatar asked Jul 22 '16 21:07

qwertylpc


People also ask

How do you add double quotes to a string in Python?

In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .

How do you use double quotes in a string?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.

How do you add double quotes to a JSON string in Python?

Alternate between single and double quotes. For example, to add double quotes to a string, wrap the string in single quotes. To add single quotes to a string, wrap the string in double quotes.

How do you add single quotes to a string in Python?

Use the escape character to put both single and double quotes in a string. Use the escape character \ before double or single quotes to include them in the string.


2 Answers

You have successfully constructed a string without the quotes. So you need to add the double quotes. There are a few different ways to do this in Python:

>>> my_str = " ".join([a.strip() for a in b.split("\n") if a])
>>> print '"' + my_str + '"'     # Use single quotes to surround the double quotes
"a b c d e f g"
>>> print "\"" + my_str + "\""   # Escape the double quotes
"a b c d e f g"
>>> print '"%s"' % my_str        # Use old-style string formatting
"a b c d e f g"
>>> print '"{}"'.format(my_str)  # Use the newer format method
"a b c d e f g"

Or in Python 3.6+:

>>> print(f'"{my_str}"')         # Use an f-string
"a b c d e f g"  

Any of these options are valid and idiomatic Python. I might go with the first option myself, or the last in Python 3, simply because they're the shortest and clearest.

like image 168
James Avatar answered Oct 12 '22 21:10

James


'"%s"' % " ".join([a.strip() for a in s.split("\n") if a])
like image 3
CentAu Avatar answered Oct 12 '22 22:10

CentAu