Finding whether a string starts with one of a list's variable-length prefixes

后端 未结 11 2078
傲寒
傲寒 2021-01-01 12:16

I need to find out whether a name starts with any of a list\'s prefixes and then remove it, like:

if name[:2] in [\"i_\", \"c_\", \"m_\", \"l_\", \"d_\", \"t         


        
11条回答
  •  -上瘾入骨i
    2021-01-01 13:08

    str.startswith(prefix[, start[, end]])¶

    Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

    $ ipython
    Python 3.5.2 (default, Nov 23 2017, 16:37:01)
    Type 'copyright', 'credits' or 'license' for more information
    IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: prefixes = ("i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_")
    
    In [2]: 'test'.startswith(prefixes)
    Out[2]: False
    
    In [3]: 'i_'.startswith(prefixes)
    Out[3]: True
    
    In [4]: 'd_a'.startswith(prefixes)
    Out[4]: True
    

提交回复
热议问题