我想扫描字符串的特定区域以查找特定单词,但我什么都想不出来。
例如:
given_word = 'I am setting this example for you to understand'
word_searching = 'for'
所以出于一个不重要的原因,我必须在特定的区域搜索。
given_word(5:10)
但是如果我写
if word_searching in given_word(5:10):
或
if word_searching in given_word(5,10):
我有错误。我该怎么解决这个问题?提前感谢
使用given_word(5:10)
是一个语法错误,需要用方括号编写given_word[5:10]
进行切片。尽管如此,还是有更好的方法。
可以为str.find
方法提供start
和stop
参数。
given_word = 'I am setting this example for you to understand'
given_word.find("for", 5, 10) # -1
given_word.find("for", 20, 30) # 26
如果没有找到序列,结果将是-1
,否则它将是找到该序列的索引。在你的情况下,你可以这样使用:
given_word = 'I am setting this example for you to understand'
word_searching = 'for'
# Check if 'for' is found in the substring given_word[5:10]
if given_word.find(word_searching, 5, 10) != -1:
...
这更有效,因为切片会创建一个新的字符串,而str.find
不会。
或者,您可以使用re.findall
:进行模式搜索
import re
given_word = 'I am setting this example for you to understand'
word_searching = 'for'
# or:
# word_searching = r'fo.'
if re.findall(word_searching, given_word[0:10]):
print('0:10')
elif re.findall(word_searching, given_word[20:30]):
print('20:30')
else:
print('not found')
# Prints:
# 20:30
尝试在given_word
单词5到10中搜索word_searching
。
given_word = 'I am setting this example for you to understand'
word_searching = 'for'
if word_searching in given_word.split(' ')[5:10]:
print(True)