简体   繁体   中英

How do you find the index of specific characters on python with multiple instances?

I'm supposed to write a function which has three parameters and then it basically has to find the instance of the third parameter in the first parameter and then it should return the first instance of the second parameter after the third parameter.

Example:

print(find_instance_character(everyone, e, v))

it should return to me the index 2 because the first e occurs before our third parameter at 1 so the function has to find the instance of the second parameter after the third.

I was thinking that I'd be using slicing or ranges here but I wouldn't know the length of the first parameter that the user enters.

Firstly, you need to input as strings print(find_instance_character('everyone', 'e', 'v'))

I would use find to get the location of the first c in a. Then splice the string and use find again to get the location of the first b relative to the first occurrence of c. Adding these gives the absolute location of the first b after the first c in a.

def find_instance_character(a,b,c):
    loc = a.find(c)
    return loc + a[loc:].find(b)

Additionally, this addition will mess up if a character is not found since -1 will be returned by find. To fix this you'll have to use an if condition to check if -1 is returned by the two find() calls.

Try find() which returns the first index of character specified in the string.

str.find(sub[, start[, end]])

sub : Required . The string searched for.

start : Optional . Search start position.

end : Optional . Search end position.

def find_instance_character(s, a, b):
    return s.find(a, s.find(b))
print(find_instance_character("everyone", "e", "v"))
# 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM