Skip to content

Instantly share code, notes, and snippets.

@angeloped
Created September 19, 2019 16:57
Show Gist options
  • Save angeloped/ec4236108ba28030dbc68c39dd75a82d to your computer and use it in GitHub Desktop.
Save angeloped/ec4236108ba28030dbc68c39dd75a82d to your computer and use it in GitHub Desktop.
Remove control characters (e.g., \n, \r, \x, etc.) with Python, compatible in both Python version 2 and 3.
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import unicodedata
def remove_CtrlChars(string):
try:# Unicode conversion for Python 2
string = string.decode("utf-8")
except:# Unicode conversion for Python 3
string = string.encode().decode("utf-8","strict")
return "".join(chars for chars in string if unicodedata.category(chars)!="Cc")
print(remove_CtrlChars("\n\n\naaaaaaлл\bклсалскссмфлскبَا\xءдхфскд"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment