[英]python find() fails to find substring at start of string
我遇到了find
一些奇怪行為。 搜索子字符串時,如果該子字符串位於我正在搜索的字符串的最開始(子字符串從索引0開始),則將找不到該子字符串。 如果我用單個空格字符填充字符串(因此子字符串從索引1開始),它將挽救find功能並表現出預期的效果。 我使用find
錯誤嗎?
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
列表中子字符串的順序似乎無關緊要。
我正在使用Python 3.6.0 :: Anaconda 4.3.0(64位)。
find
實際上按預期工作。 如果找到,應該返回字符串的索引,否則返回-1。
您的if
語句應如下所示:
for search in searches:
if my_string.find(search) >= 0:
print("Found", search)
else:
print("Did not find", search)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.