LukeP_8
LukeP_8

Reputation: 309

String indexing

Python 3.5

Here is my Code:

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    print("That word was found!")
else:
    print("Sorry, that word was not found")

As it is, it will search for the inputted word (str2) and if it is found in the input (str1 (a sentence)) it will say "the word has been found"). If the word is not in the sentence it will say "the word was not found".

I want to develop this so when the word is searched for and found, it tells the user the index position of the word (str2) in the sentence (str1). So for example: if I have the sentence ("I like to code in Python") and I search for the word ("code") the program should say "that word was found in index position: 4".

Btw the way, the code is not case sensitive as it converts all the words into lowercase with .lower.

If anyone could give me some advice on this then that would be very much appreciated!

Upvotes: 0

Views: 134

Answers (4)

Preston Martin
Preston Martin

Reputation: 2963

print("That word was found at index %i!"% (str1.split().index(str2)))

This will print the index of the first occurrence of str2 in str1.
The full code is:

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    print("That word was found!")
    print("that word was found in index position: %i!"% (str1.split().index(str2)))

, str1.index(str2))
else: print("Sorry, that word was not found")

Upvotes: 0

JDKabangu
JDKabangu

Reputation: 11

You can use a split() method: it's called on a string values and returns a list of strings. then you use index() method to find the index of the string.

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    a = str1.split() # you create a list
    # printing the word and index a.index(str2)
    print('The ', str2,' was find a the index ', a.index(str2)) 
    print("That word was found!")
else:
    print("Sorry, that word was not found")

Upvotes: 0

trincot
trincot

Reputation: 350310

You could replace your if ... else by this:

try:
    print("That word was found at index %i!"% (str1.split().index(str2) + 1))
except ValueError:
    print("Sorry, that word was not found")

Upvotes: 1

Ryan Weinstein
Ryan Weinstein

Reputation: 7285

str2 = 'abcdefghijklmnopqrstuvwxyz'
str1 = 'z'
index = str2.find(str1)
if index != -1:
    print 'That word was found in index position:',index
else:
    print 'That word was not found'

This will print the index of the str1 in str2

Upvotes: 0

Related Questions