Created
July 6, 2021 03:30
-
-
Save akkuman/394a83503f300322d23f9a0b8f215203 to your computer and use it in GitHub Desktop.
[去除不可见字符] python中去除不可见字符 #python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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