2017-08-16 61 views
0

我試圖從用戶獲取多個輸入並將其存儲在一個變量中。儲存後,我要添加字符開始和每個單詞的結尾,但我沒有得到期望的輸出在Python 3.X通過在列表中的每個項目之前和之後添加字符來獲得所需的輸出

我的代碼如下: -

string_value=[str(i) for i in raw_input("Enter space separated inputs: ").split()] 
aces = ["\'" + string_value + "\'" for string_value in string_value] 
print (aces) 

輸出: -

Enter space separated inputs: John Sunil Kathylene Bob 

["' John ' ", " ' Sunil ' ", " ' Kathylene ' ", " ' Bob' "] 

所需的輸出: -

\'John\',\'Sunil\',\' Kathylene\',\' Bob\' 
+0

你需要與其他 '\' 來esace '\'。試試這個'aces = [「\\'」+ string_value +「\\'」for string_value in string_value]' – Vinny

+0

Baxkslash是Python中的一個特殊字符。連續使用兩個反斜槓表示文字反斜槓。所以'\\'+'word' - >'\ word' – Ben

+1

第一行中的列表理解並沒有完成任何事情 - '.split()'的結果已經是一個字符串列表。 – jasonharper

回答

0

一些建議:

  • 讀PEP8。
  • 輸入strstr是多餘的。

代碼:

words = input("Enter space separated inputs: ").split() 
prefix_and_suffix = "\\'" 
formatted_words = ','.join('{0}{1}{0}'.format(
    prefix_and_suffix, word) for word in words) 
print (formatted_words) 
+1

你可以編號的佔位符,以避免重複的東西。在這種情況下,你可以這樣做:''{0} {1} {0}'。format( prefix_and_suffix,word)' –

+1

'raw_input'在Python 3中不起作用。 –

+1

他已經標記了Python3,並在他的問題中也提到了它。你只能回答他**所問的問題**,而不是你認爲他想問**的問題。 –

相關問題