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

标签 python string variable-length prefixes

我需要确定一个名称是否以列表的任何前缀开头,然后将其删除,例如:

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/

相关文章:

c++ - 可变长度模板参数列表?

python - pandas 数据框中两列的相关系数与 .corr()

regex - 在perl中分割包含经度或纬度表达式的字符串

javascript - 在php中获取特定数组字段长度

Javascript从字符串中搜索具有最大值的元素

string - 如何生成一个由字母数字字符组成的随机字符串?

Java:为什么矩阵接受大于预定义长度的行?

python - 即使引发 ValueError,Pytest assertRaisesWithMessage(ValueError) 也会失败

Python编程-从Excel工作表中查找无效记录

Python/Google 应用引擎数据存储性能