How to match substring in a string using Python
本问题已经有最佳答案,请猛点这里访问。
我有一个必须在字符串中迭代匹配的子字符串列表;如果匹配,则执行所需的功能。
问题是,每当我试图用循环访问列表时,它都不起作用。否则,如果我硬编码,它就会工作。我不明白为什么会这样?
我的代码在这里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | players_list = ['Circket', 'PSL', 'IPL', 't20', 'shahid afridi', 'aamer yamin'] length = len(players_list) cur.execute("SELECT tweet FROM tweets_data") # Query for getting specific attribute length = len(players_list) for row in cur.fetchall(): i = 0 while (i<length): #print players_list[i], 'tweet value', row if players_list[i] in row: print 'list item:', players_list[i] print row else: print 'Else statement.' i+=1 |
输出:它应该只显示和任何子字符串值匹配的行,如:
子字符串为:cricket
罗:安全官员担心板球队是以武装分子的名字命名的
你好像和
1 2 3 4 5 6 7 8 9 10 | players_list=['Cricket','PSL','IPL','t20','shahid afridi','aamer yamin'] cur.execute("SELECT tweet FROM tweets_data") # Query for getting specific attribute for row in cur.fetchall(): for player in players_list: if player.lower() in row.lower(): print 'list item:', player print row else: print 'Else statement.' |
如果我正确理解了你的问题,你可以尝试一下:
1 2 3 4 5 6 7 | players_list = ['Cricket', 'PSL', 'IPL', 't20', 'shahid afridi', 'aamer yamin'] cur.execute("SELECT tweet FROM tweets_data") for row in cur.fetchall(): if any(True for p in players_list if p.lower() in row.lower()): print(row) else: print ("Else statement") |