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.

PythonSecurity Boundaries

Code

pythonsnippet
16 lines
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

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`.