Python:查找第一个不匹配的ch

2024-06-24 13:40:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python下,当您想要获取列表中第一个出现的子字符串或字符的索引时,可以使用如下方法:

s.find("f")

但是,我想找到字符串中第一个字符的索引不匹配。目前,我正在使用以下工具:

iNum = 0
for i, c in enumerate(line):
  if(c != mark):
    iNum = i
    break

有没有更有效的方法可以做到这一点,比如我不知道的内置函数?


Tags: 工具方法字符串in列表forifline
3条回答

尽可能简单。 将print(counter)替换为python 2.x的print counter

s = "ffffff5tgbh44frff"
counter = 0
for c in s:
    counter = counter + 1
    if c != "f":
        break

print (counter)

可以使用正则表达式,例如:

>>> import re
>>> re.search(r'[^f]', 'ffffooooooooo').start()
4

[^f]将匹配除f之外的任何字符,match对象的start()方法(由re.search()返回)将给出发生匹配的索引。

为了确保您还可以处理空字符串或只包含f的字符串,您需要检查以确保re.search()的结果不是None,如果regex无法匹配,则会发生这种情况。例如:

first_index = -1
match = re.search(r'[^f]', line)
if match:
    first_index = match.start()

如果你不喜欢使用regex,你不会比你现在的方法做得更好。您可以使用类似next(i for i, c in enumerate(line) if c != mark)的内容,但您需要用tryexcept StopIteration块包装它来处理空行或只包含mark字符的行。

现在我很好奇这两个怎么回事。

>>> # map with a partial function
>>> import functools
>>> import operator
>>> f = functools.partial(operator.eq, 'f')
>>> map(f, 'fffffooooo').index(False)
5
>>> # list comprehension
>>> [c == 'f' for c in 'ffffoooo'].index(False)
4
>>>

相关问题 更多 >