[Solved] can someone explain how to use str.index and str.find and why the following code is wrong


Check the documentation

Build your code around the method:

# characters to look for in a list (string would work as well)
vowels = ["a","i","o","u","e","y"]

# a function (method)
def vowel_indices(word):
    # prepare empty list to collect the positions in
    hits = []

    # test every of your vowels
    for vowel in vowels:
        # the function returns the index of vowel in word or -1 if it's not there
        pos = word.find(vowel)
        
        # test for match
        if pos>0:
            # collect match in list
            hits.append( pos )

    # done, return the list
    return hits

# the string to analyse
word = "super"

# pass the string to the method and get its return value
results = vowel_indices(word)

# output the return value 
print(results)

Output:

[1, 3]

This is really a list object, but Python prints its elements.


As pointed out by @PM 2Ring, this only finds the first occurence of the vowel in the string. This is for two reasons:

  1. Each vowel is only tested once

  2. str.find() only finds the leftmost match (see also rfind()):

    Return the lowest index in the string where substring sub is found within the slice s[start:end].

So I pointlessly complicated the code as follows to make it work:

# characters to look for in a list (string would work as well)
vowels = ["a","i","o","u","e","y"]

# a function (method)
def vowel_indices(word):
    # prepare empty list to collect the positions in
    hits = []
    # test every of your vowels
    for vowel in vowels:
        # work on a copy
        temp = word
        # look first, give up later
        while True:
            # the function returns the index of vowel in word or -1 if it's not there
            pos = temp.lower().find(vowel)
            # test for match
            if pos>0:
                # collect match in list
                hits.append( pos )
                # remove matched vowel from
                temp = temp[:pos] + " " + temp[pos+1:]
                print(temp)
            else:
                break

    # done, return the list
    return hits

# the string to analyse
word = "Banana!"

# pass the string to the method and get its return value
results = vowel_indices(word)

# output the return value
print(results)

Output

B nana!
B n na!
B n n !
[1, 3, 5]

3

solved can someone explain how to use str.index and str.find and why the following code is wrong