我需要确定一个名称是否以列表的任何前缀开头,然后将其删除,例如:
if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
name = name[2:]
以上仅适用于长度为 2 的列表前缀。 可变长度前缀需要相同的功能。
如何高效完成(代码少,性能好)?
for 循环遍历每个前缀,然后检查 name.startswith(prefix)
以最终根据前缀的长度对名称进行切片,但它的代码很多,可能效率低下,和“非 Pythonic”。
有人有好的解决方案吗?
最佳答案
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
关于python - 查找字符串是否以列表的可变长度前缀之一开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7539959/