-2

When the user is asked to search for a word, I want it to be case-insensitive.

import string
usersentence= input("Please type in a sentence without punctuation: ")

usersentence = ''.join(ch for ch in usersentence if ch not in set(string.punctuation))
print (usersentence.upper())
for i in range(1):      # number of words you wont to search
    word= input("Please enter a word you want to search for in the sentence: ")
    words = usersentence.split(' ')
    passed = False      # Something to check if the word is found
    for (i, words) in enumerate(words):
        if (words == word): 
            print("your word appears in position(s): ")
            print(i+1)
            passed = True       # The word has been found

    if not passed:
        print("Sorry your word does not seem to be here")
halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

1

There is no need to split your sentence in separate words first. You can first check:

if word.upper() in usersentence.upper():
    wordlist = usersentence.upper().split('')
    solution = [i for i, sentword in enumerate(wordlist) if sentword == word.upper()]
vds
  • 349
  • 1
  • 10
1

Your question sounds strange since your code partially contains the solution :-) ! You can either use str.upper() or str.lower() to compare strings with no case constraints, just as you print one of them using str.upper(). Your code should then contain lines transformed this way:

word=input("Please enter etc.").lower()  # or .upper(), as you wish
# ...
for (i, word_) in enumerate(words):
    if (word_.lower() == word):  # or word_.upper(), as you wish

Using str.lower() should keep track of any accentuated char (useful in many languages). As a French speaker, this is the method I recommand. But str.upper() should fit your needs also. See section 3.13 of the Unicode Standard to get information on how lower() and upper() are working on special chars.

Schmouk
  • 327
  • 2
  • 6
1

use string.lower() while comparing strings

use while loop to repeat the code

use break to break a loop

while True:
    sent = raw_input("Enter Sentence: ").lower() #or upper()
    sent = sent.split()

    word = raw_input("Enter Word to search: ").lower() #or upper()
    indexes= []
    for idx,ele in enumerate(sent):
        if word == ele:
            indexes.append(str(idx))
    print ("Your word appears at indexes: "+", ".join(indexes))

    response = raw_input("Do you want to continue? Y/N: ").lower()
    if response == 'n':
        break
    else:
       pass

The above code asks for user inputs and then checks if the word exists in given sentence, it then asks for confirmation to continue or not. If the user says N or 'n' then the loop breaks and program exits. If user says Y or 'y' then it asks for sentence and word again.

Edit: Replaced continue variable name with response

Harwee
  • 1,601
  • 2
  • 21
  • 35