查找字符串是否以列表的可变长度前缀之一开头

Kaw*_*awu 21 python string prefixes variable-length

我需要找出一个名称是否以列表的任何前缀开头,然后删除它,如:

if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
    name = name[2:]
Run Code Online (Sandbox Code Playgroud)

以上仅适用于长度为2的列表前缀.我需要与可变长度前缀相同的功能.

如何有效地完成(代码少,性能好)?

一个for循环迭代每个前缀,然后检查name.startswith(prefix)最终根据前缀的长度切片名称,但它是很多代码,可能效率低,而且"非Pythonic".

有没有人有一个很好的解决方案?

dm0*_*514 40

str.startswith(前缀[,start [,end]])

如果字符串以前缀开头,则返回True,否则返回False.前缀也可以是要查找的前缀元组.使用可选的启动,测试字符串从该位置开始.使用可选结束,停止比较该位置的字符串.

$ 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
Run Code Online (Sandbox Code Playgroud)

  • 是的,因为它接受元组,它可能是最干净的实现. (6认同)

Vau*_*ato 13

有点难以阅读,但这有效:

name=name[len(filter(name.startswith,prefixes+[''])[0]):]
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 5

for prefix in prefixes:
    if name.startswith(prefix):
        name=name[len(prefix):]
        break
Run Code Online (Sandbox Code Playgroud)