如何检查数组中的任何字符串是否存在于另一个字符串中?
喜欢:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
Run Code Online (Sandbox Code Playgroud)
该代码不起作用,只是为了展示我想要实现的目标.
我有一个python中的正则表列表和一个字符串.有没有一种优雅的方法来检查列表中的至少一个正则表达式是否与字符串匹配?通过优雅,我的意思是比简单地循环遍历所有正则表达式并检查字符串并在找到匹配时停止更好.
基本上,我有这个代码:
list = ['something','another','thing','hello']
string = 'hi'
if string in list:
pass # do something
else:
pass # do something else
Run Code Online (Sandbox Code Playgroud)
现在我想在列表中有一些正则表达式,而不仅仅是字符串,我想知道是否有一个优雅的解决方案来检查匹配替换if string in list:.
提前致谢.
找到关于如何检查字符串列表是否在一行内的这个很好的答案如何检查 一行是否有列表中的一个字符串?
但是尝试用dict中的键做类似的事情似乎并不适合我:
import urllib2
url_info = urllib2.urlopen('http://rss.timegenie.com/forex.xml')
currencies = {"DKK": [], "SEK": []}
print currencies.keys()
testCounter = 0
for line in url_info:
if any(countryCode in line for countryCode in currencies.keys()):
testCounter += 1
if "DKK" in line or "SEK" in line:
print line
print "testCounter is %i and should be 2 - if not debug the code" % (testCounter)
Run Code Online (Sandbox Code Playgroud)
输出:
['SEK', 'DKK']
<code>DKK</code>
<code>SEK</code>
testCounter is 377 and should be 2 - if not debug the code
Run Code Online (Sandbox Code Playgroud)
想想也许我的问题是因为.keys() …