我遇到了find
的一些奇怪行为。在搜索子字符串时,如果该子字符串位于我正在搜索的字符串的最开头(子字符串从索引0开始),则不会找到它。如果我用一个空白字符填充字符串(因此子字符串从索引1开始),它会挽救查找功能并按预期运行。我错误地使用my_string = "hello world"
searches = ["hello",
"world",
]
# Search the string for the two substrings
for search in searches:
if my_string.find(search):
print("Found", search)
else:
print("Did not find", search)
# Did not find hello
# Found world
# Try padding the string, so substring 'hello' is not at the very beginning
my_padded_string = " " + my_string
for search in searches:
if my_padded_string.find(search):
print("Found", search)
else:
print("Did not find", search)
# Found world
# Found hello
吗?
searches
请注意{{1}}列表中子字符串的顺序似乎并不重要。
我使用的是Python 3.6.0 :: Anaconda 4.3.0(64位)。
答案 0 :(得分:2)
find
实际上是按预期工作的。如果找到则返回字符串的索引,否则返回-1。
您的if
声明应如下所示:
for search in searches:
if my_string.find(search) >= 0:
print("Found", search)
else:
print("Did not find", search)