replace Rewrites A Bounded Count
str.replace accepts an optional count that limits replacement to the first N occurrences, enough for tiered masking without splitting strings.
Code
log_line = 'token=abc token=abc token=abc'
# 不给 count:所有出现都被替换
print(log_line.replace('abc', '***'))
# 给 count:只替换前 N 处,其余原样保留
print(log_line.replace('abc', '***', 1))
print(log_line.replace('abc', '***', 2))
# count=0 什么都不替换;找不到子串也不报错
print(log_line.replace('abc', '***', 0))
print(log_line.replace('xyz', '***'))
# 分级脱敏:第一处保留首字符便于对账,其余整段遮蔽
masked = log_line.replace('abc', 'a**', 1).replace('abc', '***')
print(masked)Output
Captured from a sandboxed run of this snippet in the build pipeline.
token=*** token=*** token=***
token=*** token=abc token=abc
token=*** token=*** token=abc
token=abc token=abc token=abc
token=abc token=abc token=abc
token=a** token=*** token=***replace Rewrites A Bounded Count: inside the code
The top-level bindings are the whole world here: log_line, masked.
Points of care
- No imports outside what the runtime already ships.
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `log_line`, `masked`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.