2016-09-26 71 views
0

我想從我的名單上單獨的行打印每一個字,但它是打印出每一個字母到各行如何在列表中打印單個單詞?

Words = sentence.strip() 
for word in sentence: 
    print (word) 

我完整的代碼(任何人都知道)是:

import csv 
file = open("Task2.csv", "w") 
sentence = input("Please enter a sentence: ") 
Words = sentence.strip() 
for word in sentence: 
    print (word) 
for s in Words: 
    Positions = Words.index(s)+1 
    file.write(str(Words) + (str(Positions) + "\n")) 
file.close() 
+0

使用'.split()'和'.strip()' –

+0

有關問題請使用http://codereview.stackexchange.com – esote

+0

不要使用'.index()'作爲位置,只返回第一個位置(如果你有重複的字母),使用'enumerate()相反 –

回答

0

你忘記分句,並在第一個循環中使用「單詞」而不是「句子」。

#file = open("Task2.csv", "w") 
sentence = input("Please enter a sentence: ") 
Words = sentence.split() 
for word in Words: 
    print (word) 
for s in Words: 
    Positions = Words.index(s)+1 
    #file.write(str(Words) + (str(Positions) + "\n")) 
#file.close() 

輸出:

C:\Users\dinesh_pundkar\Desktop>python c.py 
Please enter a sentence: I am Dinesh 
I 
am 
Dinesh 

C:\Users\dinesh_pundkar\Desktop> 
0

您需要使用str.split(),而不是str.strip()

str.strip()只刪除一個字符串的開頭和結尾的空格:

>>> my_string = ' This is a sentence. ' 
>>> my_string.strip() 
'This is a sentence.' 

str.split()你想要做什麼是返回字符串中的單詞列表;默認情況下,使用空格作爲分隔字符串:

>>> my_string = ' This is a sentence. ' 
>>> my_string.split() 
['This', 'is', 'a', 'sentence.'] 

所以,你的代碼應該看起來更像是:

words = sentence.split() 
for word in sentence: 
    print(word) 
相關問題