2016-07-22 120 views
-1

如果我输入的文本是双引号字符串添加在python

a 
b 
c 
d 
e 
f 
g 

,我想我的输出文本是:(带双引号)

"a b c d e f g" 

我在哪里后,此去步:

" ".join([a.strip() for a in b.split("\n") if a]) 
+0

把''“”“,'放在连接语句的前面 – Natecat

+1

你试过了吗? – TigerhawkT3

回答

6

您已成功构建了没有引号的字符串。所以你需要添加双引号。有几种不同的方式在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 string formatting 
"a b c d e f g" 

所有这些选项都有效,地道的Python。我可能会自己选择第一个选项,因为它简短明了

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