2016-09-26 4 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

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

+0

に関する質問:

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

だから、あなたのコードはより多くのようになりますコードをより効率的にするには、http://codereview.stackexchange.comにアクセスしてください。 – esote

+0

位置に '.index()'を使わず、最初の位置だけを返します(文字が重複している場合)。 'enumerate '代わりに –

答えて

0

あなたは文を分割して最初のforループで "sentence"ではなく "Words"を使うのを忘れてしまった。

#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()は、文字列内の単語のリストを返すとする何をしたいん。デフォルトでは、区切り文字列として空白文字を使用して:

words = sentence.split() 
for word in sentence: 
    print(word) 
関連する問題