2016-09-26 70 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) 
相关问题