簡體   English   中英

Python在字符串中查找索引

[英]Python find index in a string

我正在嘗試在下面的此字符串中打印單詞的索引。 現在的問題是它正在檢查列表中的每個元素並返回false。 如果單詞不在列表中並且不檢查每個元素,如何使它返回“ False”?

target = "dont"
string = "we dont need no education we dont need to thought control no we dont"
liste = string.split() 
for index, item in enumerate(liste):
        if target in item:
                print index, item
        else:
                print 'False'

輸出:

False
1 dont
False
False
False
False
6 dont
False
False
False
False
False
False
13 dont

首先檢查單詞是否在列表中:

 if word not in liste:

因此,如果要返回,請將其放在函數中:

def f(t, s):
    liste = s.split()
    if t not in liste:
        return False
    for index, item in enumerate(liste):
        if t == item:
            print index, item
    return True

除非要匹配子字符串,否則if t == item:也應該匹配,如果要返回所有索引,則可以返回list comp:

def f(t, s):
    liste = s.split()
    if t not in liste:
        return False
    return [index for index, item in enumerate(liste) if t == item]

我認為這是您想要的:

target = "dont"
string = "we dont need no education we dont need to thought control no we dont"
liste = string.split()
if target in liste:
    for index, item in enumerate(liste):
        if target == item:
            print index, item
else:
    print 'False'

暫無
暫無

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

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