简体   繁体   中英

Add double quotes to string in python

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

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.

'"%s"' % " ".join([a.strip() for a in s.split("\n") if a])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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