简体   繁体   中英

Printing the rest of a string after the second occurrence of a substring

I am trying to print out the remaining string after finding the second occurrence of another string inside the original.

My code:

    def after_second(target, search):
        count = 0
        start = target.find(search)
        while start >=0:
            count +=1
            start +=1
            if count == 2:
                return target[start:]

    print(after_second("11223344554321", "3"))
    print(after_second("heyyoheyhi!", "hey"))

This code should be outputting:

44554321

hi!

however I am getting back:

44554321

yyoheyhi!

Splitting the sting with a maximum of 2 splits will make the 3rd part contain what you need:

"heyyoheyhi!".split("hey",2)[2] --> "hi!"

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