ActiveState Code

Recipe 576602: safe print


A replacement for "print" that will safely handle unicode conversion.

Python
1
2
3
4
5
6
7
8
def _safe_print(u, errors="replace"):
    """Safely print the given string.
    
    If you want to see the code points for unprintable characters then you
    can use `errors="xmlcharrefreplace"`.
    """
    s = u.encode(sys.stdout.encoding or "utf-8", errors)
    print(s)

Sign in to comment