2017-01-29 9 views
1

私はstr1として定義されている文章を入力するようにユーザに指示し、str2として定義された単語を入力するよう促されます。例えばPython 3のforループを使用した文字列の値の検索

私はSTR1でSTR2を見つけるためにforループを使用したい
Please enter a sentence: i like to code in python and code things 
    Thank you, you entered: i like to code in python and code things 
    Please enter a word: code 

、それは言葉が/発見されていないいるかどうかを印刷し、それが発見された場合、インデックス位置するためstr2の値を返します。

は現在、私はこのコードを持っている:

str1Input = input("Please enter a sentence: ") 
    print("Thank you, you entered: ",str1Input) 

    str1 = str1Input.split() 

    str2 = input("Please enter a word: ") 

    for eachWord in str1: 
     if str2 in str1: 
      print("That word was found at index position", str1.index(str2)+1) 
     else: 
      print("Sorry that word was not found") 

結果は文中の単語ごとに一度STR1内の単語は単語のインデックス値で見つかったかどうかを印刷するに見えますが?例えば、str1が「りんごオレンジレモンのライム梨」だったと私はそれが思い付くだろう単語「りんご」を選択した場合:誰も私となり、これに似た何かをしようと誰を助けることができれば

That word was found at index position: 1 
    That word was found at index position: 1 
    That word was found at index position: 1 
    That word was found at index position: 1 
    That word was found at index position: 1 

非常に便利です!ありがとう! :)

+0

はただ与えられた文字列の位置検索ワードを見つけることについて、それをですか? – RomanPerekhrest

+0

はい、正解です。指定された文字列に同じ単語が2つ以上ある場合でも、インデックス位置をすべて印刷できるようにしてください –

+0

スペースで区切っている場合、どのように単語を繰り返すことができますかリストの1つの要素ですか?あなたがcancanのような言葉を持っていて、canという言葉を探していない限り。また、 'eachWord for str1:'のループをループし、 'eachWord'を使用しないでください!あなたは各繰り返しで同じ検索をしています。 –

答えて

1

コードの問題はです。つまり、すべての単語ではなく文字str1に繰り返します。これを解決するには、単語を区切るのにstr1.split()を使います。また、ループの外側にif str2 in str2を置く必要があります。 str2str1にあるかどうかを確認し、str1を反復するのではなく、str1を繰り返して、が含まれているかどうかを確認します。単語が複数回使用されると、使用できなくなります。 str1.split().index()はすべての位置を検索します。index()は常にリスト内の項目の最も低い位置を返します。

簡単にメソッドが使用するlist comprehension

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2] 

これはstr1.split()str2のすべてのインデックスが含まれています。

決勝コード:

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2] 
if positions: 
    for position in positions: 
     print("That word was found at index position",position) 
else: 
    print("Sorry that word was not found") 

入力:

Please enter a sentence: i like to code in python and code things 
Thank you, you entered: i like to code in python and code things 
Please enter a word: code 

出力:

That word was found at index position 3 
That word was found at index position 7 
+0

返信いただきありがとうございます。私は私のforループメソッドを使用してコードを編集し、単語のインデックス位置を印刷する方法を見つけることができましたが、文中の索引位置の総数に対する索引位置も含まない)。これは一歩前進です。好ましくはforループメソッドを使用して、インデックス位置を一度印刷して、それが複数回文章に記載されている場合はその単語のインデックス位置を出力する方法がありますか?新しいコードが質問ボックスにあります –

関連する問題