2016-07-22 119 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])