需要在python中搜索字符串中的“双字”模式

时间:2018-04-06 01:36:57

标签: python

我正在尝试搜索一长串字符以查找国家/地区名称。国名有时不止一个字,例如哥斯达黎加。

这是我的代码:

eol = len(CountryList)
for c in range(0, eol):
   country = str(CountryList[c])
   countrymatch = re.search(country, fullsampledata)
   if countrymatch:
      ...

fullsampledata是一个长字符串,其中所有数据都在一行中。我试图通过一系列有效的国家名称来循环解析这个国家。如果国家只有一个词,例如“荷兰”,它就会找到它。但是,如果国家是两个或更多的单词,'哥斯达黎加',它找不到它。为什么呢?

2 个答案:

答案 0 :(得分:1)

您可以使用.find()函数在字符串中搜索子字符串,如下所示

fullsampledata = "hwfekfwekjfnkwfehCosta Ricakwjfkwfekfekfw"
fullsampledata.find("Morocco")
  

-1

fullsampledata.index("Costa Rica")
  

17

所以你可以按如下方式制作你的if语句

fullsampledata = "hwfekfwekjfnkwfehCosta Ricakwjfkwfekfekfw"
country = "Costa Rica"
if fullsampledata.index(country) != -1:
   # Found
   pass
else:
   # Not Found
   pass

答案 1 :(得分:0)

In [1]: long_string = 'asdfsadfCosta Ricaasdkj asdfsd asdjas USA alsj'

In [2]: 'Costa Rica' in long_string
Out[2]: True

您没有正确显示您的代码,而且我有点懒得解析它。希望这会有所帮助。