str.translate Remaps Text Via maketrans

Clean pasted text with str.maketrans and str.translate: map curly quotes, delete control characters, and remap code points in one pass per table.

PythonData Integrity

Code

pythonsnippet
16 lines
# str.maketrans 三种形态:字典映射、删除集合、等长码点替换
normalize = str.maketrans({"‘": "'", "’": "'", "“": '"', "”": '"', "\t": " "})
drop = str.maketrans("", "", "\r\x0b\x0c")  # 第三参里的字符直接删除
circled = str.maketrans("0123456789", "⓪①②③④⑤⑥⑦⑧⑨")

raw = "It’s “ready”\tfor review\r"  # 粘贴进来的文本常带 tab 与行尾 CR
clean = raw.translate(normalize).translate(drop)
print(repr(raw))
print(repr(clean))

# 组合出标识符净化表:点号与空格统一为下划线,删除百分号
identifier = str.maketrans(". ", "__", "%")
print("user.profile v2%.bak".translate(identifier))

# 同一张表可复用:等长替换按码点逐字符重映射
print("stage 2/9".translate(circled))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

'It’s “ready”\tfor review\r'
'It\'s "ready" for review'
user_profile_v2_bak
stage ②/⑨

How it works

Module-level bindings hold the data — normalize, drop, circled, raw — with no function scope in between.

Putting it to use

Look for the user.profile v2, stage 2/9 prefixes when the file runs; they tie each line to its step.

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `normalize`, `drop`, `circled`.