簡體   English   中英

具有多個子字符串的find()-Python

[英]find() with multiple substrings - Python

如何找到字符eo的第一個匹配項?

我想做這樣的事情:

my_string = "Hello World"
x = my_string.find('e' or 'o',my_string)
print x # 1

enumerate函數與生成器表達式一起使用,像這樣

>>> next(idx for idx, char in enumerate("Hello World") if char in 'eo')
1

它將給出第一個字符的索引,即eo

注意:如果字符串中沒有字符,它將失敗。 因此,您可以選擇傳遞默認值,例如

>>> next((idx for idx, char in enumerate("Hello World") if char in 'eo'), None)
1
>>> next((idx for idx, char in enumerate("Hi") if char in 'eo'), None)
None

或者,你可以做一個find每個字符,然后取最小值所有結果(扔掉-1小號,除非他們都是-1 ):

def first_index(string, search_chars):

    finds = [string.find(c) for c in search_chars]
    finds = [x for x in finds if x >= 0]

    if finds:
        return min(finds)
    else:
        return -1

這樣產生:

>>> first_index("Hello World", "eo")
1
>>> first_index("Hello World", "xyz")
-1

您可以使用collections.defaultdict

>>> import collections
>>> my_dict = collections.defaultdict(list)
>>> for i,x in enumerate("hello world"):
...     if x in "eo":
...         my_dict[x].append(i)
... 
>>> my_dict
defaultdict(<type 'list'>, {'e': [1], 'o': [4, 7]})
>>> my_dict['e'][0]     # 1st  'e'
1
>>> my_dict['o'][0]     # 1st 'o'
4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM