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

后端 未结 4 1464
梦毁少年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条回答
  •  长情又很酷
    2020-12-20 12:26

    I would favour the re module as it's built in and already tested. It's also optimised for exactly this kind of thing.

    >>> import re
    >>> re.search(r'[ !]', 'Hello World!').start()
    5
    

    You probably want to check that a match was found though or catch the exception when it's not.

    There are reasons for not using re, but I would want to see a good comment justifying the rational. Thinking that you can "do it better" is generally unnecessary, makes it harder for others to read the code and is less maintainable.

提交回复
热议问题