简体   繁体   中英

Find last occurrence of character in string without built-in function

I need to make a function in Python 2.7 that does not use any built-in functions to find the last occurrence of a character in a string. It should work like:

string="This is a string with plenty of eeeeees"
string.rfind("e")

But the .rfind has to be replaced with a function created in the code like:

def lastocc(string, char):
    # Function code

The below code will iterate over your string, and if it finds the matching character updates the found_at variable with the index of it in the string. It also uses the common idiom of returning -1 if the character is not present in the string.

def last_occurence(s, char):
    found_at = -1
    index = 0
    for s_char in s:
        if s_char == char:
            found_at = index
        index += 1

    return found_at

If you could use the len() built-in, you could start your iteration from the end of the string, and take the length-negative_index to find it instead.

I hope that there is not too much built-in functions:

    def lastocc(string, char):
       m=-1;
       i=0;
       while i>=0:
          try:
             if string[i]==char:
                m=i;
             i+=1
          except Exception:
             i=-1;
       return(m);

   print(lastocc("1234561234", "0"))
def lastocc(somestr, char):
    return max(i for i,c in enumerate(somestr) if c==char)

Or if you don't want to use any builtins whatsoever, you could do this:

def lastocc(somestr, char):
    if not somestr: return -1
    if somestr[-1] == char: return len(somestr)-1
    return lastocc(somestr[:-1], char)

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