实现说明
顶层就这几处状态:header。
使用要点
- 演示输出是带标签的(
index raises:),每个操作都会留下自己的一行标注。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件用顶层绑定保存自己的状态:header。
核心语句
except ValueError as exc:
print("index raises:", exc)
代码示例
header = 'Retry-After: 30, ETag: "a=b"'
# partition makes only the first cut: the header and the whole value separate safely, and colons or equals inside the value survive
name, sep, value = header.partition(":")
print(name, "|", sep, "|", value)
# rpartition cuts from the right: it takes everything after the last separator
filename, dot, ext = "archive.backup.tar.gz".rpartition(".")
print(filename, "|", ext)
# missing separator: it returns (the original string, '', ''), so callers skip the membership check
user, sep, domain = "local-only".partition("@")
print(repr(user), repr(sep), repr(domain))
# contrast: split cuts at every separator, and index throws ValueError outright on a miss
print(header.split(":"))
try:
"local-only".index("@")
except ValueError as exc:
print("index raises:", exc)