2016-04-26 7 views
-1

私は「ワードファインダー」のようなスクリプトを作っています。ここには単語を入力することができ、その単語が見つかった位置が返されます。しかし、単語がそれ以上出現すると、私はそれを言いたくなりません。Pythonでどのようにコンマを追加し、整然とした方法で追加しますか?

この言葉は、位置(複数可)で発生します:私はそれが言いたい

... 3と4と5:

この言葉は、位置(S)に発生した3 、4および5 ...

0123現時点で

、それは二つの位置がある場合単語が発生した、戻り...

これを図3及び図4と:

この単語は、位置(複数可)で発生私のコードは、これまでのところです:

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" 

List=[] 

for i in sentence.split(" "): 
    List.append(i) 

print(sentence) 

position = "Your word is found in position(s): " 

keyword = input("Please enter a word you want to find the position of. ").upper() 

times=0 

for i in range (len(List)): 
    if keyword in List[i]: 
     i=i+1 
     times=times+1 
     found=str(i) 
     position = position + found + " and " 

if times==0: 
    print("The word was not found.") 
else:  
    print(position) 

答えて

0
  • がリスト
  • ストアを作成し、すべてのポジションWHEあなたはその言葉を見つける。
  • 新しいresult文字列を作成します。
  • リストに反復する
  • 各単語をresult文字列に追加します。
  • 単語がn - 1の場合は、andを追加し、そうでない場合は,を追加します。単語nを処理している場合は、何も追加しないでください。
  • 最後に、印刷結果の文字列。

これは一般的なプログラミング手法です。私は確かに、エレガントなpythonの解決策があるでしょう。

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" 
words = sentence.split(' ') 

positions = [] 
print (sentence) 
keyword = raw_input("Please enter a word you want to find the position of. ").upper() 

i = 0 
for i in range(len(words)): 
    if keyword in words[i]: 
    positions.append(i) 

if len(positions): 
    result = '' 

    n = len(positions) 

    i = 0 
    while i < n: 
    result += str(positions[i]) 
    if i == n - 2: 
     result += ' and ' 
    elif i < n - 2: 
     result += ', ' 
    i += 1 
    print(result) 

else:  
    print("The word was not found.") 
+0

これは非常に非Python的です。 –

1

ループ中に文字列を見つけた位置を記録し、後でフォーマットします。

if len(found) == 1: 
    position += "{}".format(found[0]) 
else: 
    # This will put a comma between everything except the last entry 
    position += ", ".join(found[0:-1]) 
    # Then we add the last entry 
    position += " and {}".format(found[-1]) 
1

Python文字列ことができる非常に素敵な参加機能を持っています。その後、ループが行われた後、このようなものが

は、あなたが場所のリストを found作ると言うと、ループ内で、あなたは found.append(str(i))を行うだろうリストアイテム間にセパレータを追加するのに役立ちます。追加したいので「と」最後の項目の前に、あなたはこれを作るの組み合わせ参加し、最後の1を追加する前に、「追加」を追加使用して、最後のものを除くすべての項目...

に参加することができます。

if not List: 
    print("The word was not found.") 
else: 
    msg = "Your word is found in position(s): " 
    if len(List) > 1: 
     msg = msg + ', '.join([str(i) for i in List[:-1]]) + ' and ' 
    print(msg + str(List[-1])) 

しかし、それはあなたがまだあなたが使用できる代わりにposition(s)を使用していることを恥のビットです:

if not List: 
    print("The word was not found.") 
else: 
    if len(List) > 1: 
     print("Your word is found in positions:", ', '.join([str(i) for i in List[:-1]]), 'and ', str(List[-1])) 
    else: 
     print("Your word is found in position:", str(List[0])) 
関連する問題