find Returns Minus One, index Raises
Locate substrings with str.find when absence is expected and str.index when it is not, while the in operator answers pure membership without a position.
Code
log_line = "GET /healthz 200 - upstream=fast"
print(log_line.find("200")) # 位置
print(log_line.find("500")) # 缺失 -> -1,不抛异常
try:
log_line.index("500")
except ValueError as e:
print("index raised:", e)
# 只想知道“有没有”,用 in:不产生位置
print("upstream" in log_line, "grpc" in log_line)
# rfind 从右往左找,配合切片取最后一段
last = log_line.rfind("=")
print("tail:", log_line[last + 1:])
# find 接受 start 参数:跳过前面的匹配继续找
first_at = log_line.find("0")
second_at = log_line.find("0", first_at + 1)
print("zeros at", first_at, "and", second_at)Output
Captured from a sandboxed run of this snippet in the build pipeline.
13
-1
index raised: substring not found
True False
tail: fast
zeros at 14 and 15The shape of the snippet
Demo state sits in top-level bindings: log_line, last, first_at, second_at.
What to watch for
- Entirely standard-library — copy it in and it runs.
Using it
Expect labeled output — index raised:, upstream, tail: — when the file runs.
Key statements
except ValueError as e:
print("index raised:", e)
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `log_line`, `last`, `first_at`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.