How to find the first index of any of a set of characters in a string

后端 未结 4 1452
梦毁少年i
梦毁少年i 2020-12-20 11:44

I\'d like to find the index of the first occurrence of any “special” character in a string, like so:

>>> \"Hello world!\".index([\' \', \'!\'])
5
         


        
4条回答
  •  旧时难觅i
    2020-12-20 12:22

    Not as optimized as Padraic Cunningham's solution, but still a one liner:

    string = "Hello world!"
    specials = [' ', '!', 'x']
    min(map(lambda x: (string.index(x) if (x in string) else len(string)), specials))
    

提交回复
热议问题