string.find 在列表中不起作用
我遇到了一个关于 string.find
的奇怪问题。
我有一个这样的列表:
lstofpro = ["Brown, John", "Smith,Jon"]
keywordstring = "Something: Smith,Jon Account Number: 99999"
for p in lstofpro:
if keywordstring.find(p.strip()) != -1:
print ("Found a match for : %s" % p)
上面的代码即使在 keyworstring
中存在这个值,也找不到匹配。如果我把 p.strip()
改成直接写的 "Smith,Jon",它就能成功找到。
大家有没有想过可能是什么问题呢?
1 个回答
1
你有没有想过为什么不能用“in”这个操作符呢?我试着用它来做你的算法,结果得到了想要的结果:
lstofpro = ["Brown, John", "Smith,Jon"]
keywordstring = "Something: Smith,Jon Account Number: 99999"
for p in lstofpro:
if p in keywordstring:
print ("Found a match for : %s" % p)