python - 获取字符串中集合中任意字符的第一次出现 - python

标签 python python-2.7

是否有更好的方法来查找某个字符的第一次出现:'x'、'y'、'z' 在 someStr 中?

def findFirstAppearance(someStr):
    x = someStr.find('x');
    y = someStr.find('y');
    z = someStr.find('z');

    if x == -1: x= len(someStr);
    if y == -1: y= len(someStr);
    if z == -1: z= len(someStr); 

    return min(x,y,z);

例如:对于 someStr = "axby"它应该返回 1。 对于 someStr = "aybx"它也应该返回 1。

谢谢!

最佳答案

也许:

>>> s = 'this string x contains y several letters z'
>>> next(i for i,c in enumerate(s) if c in 'xyz')
12
>>> s[12]
'x'

如果未找到,这将引发异常,这可以通过使用默认值来修复:

>>> next(i for i,c in enumerate(s) if c in 'Q')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next((i for i,c in enumerate(s) if c in 'Q'), -1)
-1

您还可以预先构建一个集合来测试以下位置的成员资格:

>>> special = set("vmp")
>>> next((i for i,c in enumerate(s) if c in special), -1)
27

如果有很多字母需要测试,可能会更快;这在很大程度上取决于所涉及的尺寸。如果重要的话很容易进行实验,但是(剧透警告)它可能并不重要。

关于python - 获取字符串中集合中任意字符的第一次出现 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662516/

相关文章:

python - scapy 操作系统错误 : [Errno 9] Bad file descriptor

python - 找出列表中每个项目的对象类型的最佳方法

python - 在函数内使用字典

javascript - 如何将Python创建的JSON数据发送到JavaScript?

python - Datadog python api错误信息未找到代理或无效的配置文件

python - 属性错误 : 'module' object has no attribute 'to_rgb'

python-2.7 - Python 电子邮件模块 ImportError : No module named utils

python - PyQT:获取 QListWidgetItem 内的内容 CustFormWidgetIem

python - 查看 multiprocessing.queue?

Python shlex 没有右引号错误——如何处理?