Skip to content

Instantly share code, notes, and snippets.

@babo
Created November 4, 2014 16:11
Show Gist options
  • Save babo/d20d418d285295e733c7 to your computer and use it in GitHub Desktop.
Save babo/d20d418d285295e733c7 to your computer and use it in GitHub Desktop.
Unicode encoding exceptions
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def try_to(text):
try:
after = text.encode('ascii')
except UnicodeEncodeError:
after = text.encode('utf-8')
except UnicodeDecodeError:
after = text
except Exception as exc:
print type(exc), exc
print type(text), type(after), after
def main():
for k in ['szia', u'szia', u'Öt szép szűzlány őrült írót nyúz']:
try_to(k)
if isinstance(k, unicode):
try_to(k.encode('utf-8'))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment