我有一个字符串列表,我需要找出'American'
是否在该字符串中。如果存在,那么我想找出美式单词的开始和结束索引
['Here in Americans, people say “Can I get a bag for the stuff?”',
'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',
'When mixing coffee, people in American use creamer, which is equivalent of milk.']
所需的输出:找出美式单词的开始和结束索引
8,16
75,83
30,38
您可以使用re.search
,它返回具有一个start
方法和一个end
方法的匹配对象,该方法和方法返回您要查找的内容:
import re
l = [
'Here in Americans, people say “Can I get a bag for the stuff?”',
'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',
'When mixing coffee, people in American use creamer, which is equivalent of milk.',
'Hello World'
]
for string in l:
match = re.search('American', string)
if match:
print('%d,%d' % (match.start(), match.end()))
else:
print('no match found')
输出:
8,16
75,83
30,38
no match found
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句