Skip to content

Instantly share code, notes, and snippets.

@akkuman
Created July 6, 2021 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkuman/394a83503f300322d23f9a0b8f215203 to your computer and use it in GitHub Desktop.
Save akkuman/394a83503f300322d23f9a0b8f215203 to your computer and use it in GitHub Desktop.
[去除不可见字符] python中去除不可见字符 #python
# ref: https://stackoverflow.com/a/54451873
import sys
# build a table mapping all non-printable characters to None
NOPRINT_TRANS_TABLE = {
i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()
}
def make_printable(s):
"""Replace non-printable characters in a string."""
# the translate method on str removes characters
# that map to None from the string
return s.translate(NOPRINT_TRANS_TABLE)
assert make_printable('Café') == 'Café'
assert make_printable('\x00\x11Hello') == 'Hello'
assert make_printable('') == ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment