2014-10-29 392 views
0
def catenateLoop(strs): 
    outputString = "" 
    for strings in strs: 
     outputString = outputString + strings   
    print outputString 

我正在使用上面的代碼連接到使用for循環的單個字符串的列表中的字符串。沒有代碼輸出正確的連接,但由於某種原因,代碼沒有作爲字符串輸出。例如,catenateLoop(['one','two','three'])正在打印onetwothree而不是'onetwothree'。我嘗試了幾種不同的格式,但我似乎無法弄清楚爲什麼它不會打印在字符串中。有任何想法嗎?For循環python將不會打印輸出作爲字符串

+0

打印字符串不包括引號。它仍然是一個字符串。 – 2014-10-29 21:00:08

+0

如果你想看到字符串周圍的引號,請在兩邊添加引號字符串:'print''「+ outputString +」'「' – 2014-10-29 21:00:50

回答

0

「print」只打印出outputString的內容;如果你想輸出outputString(它將包含引號)的表示,請嘗試「print repr(outputString)」。

0

__repr__來救援!

這會給你想要的結果

def catenateLoop(strs): 
    outputString = "" 
    for strings in strs: 
     outputString = outputString + strings   
    print repr(outputString) 

catenateLoop(['one', 'two', 'three']) 

#output: 'onetwothree' 

另見Why are some Python strings are printed with quotes and some are printed without quotes?

+0

如果我想要一個定義的輸出,我不會依賴'repr'。 – Matthias 2014-10-29 21:30:11

+0

@Matthias你能告訴我你定義的輸出是什麼意思嗎? – 2014-10-29 21:34:26

+0

'repr'爲您提供對象的可打印表示,並且此表示可能會在將來版本的Python中(或通過猴子修補)進行更改。我會用它來進行調試,但不能得到明確的輸出。 – Matthias 2014-10-30 07:12:05

0

您可以使用str.format,敷在任何你想要的輸出:

def catenateLoop(strs): 
    outputString = "" 
    for strings in strs: 
     outputString = outputString + strings 
    print "'{}'".format(outputString) 

In [5]: catenateLoop(['one', 'two', 'three']) 
'onetwothree' 

您還可以使用str.join連接列表內容:

def catenateLoop(strs): 
    print "'{}'".format("".join(strs))