Skip to content

Instantly share code, notes, and snippets.

@nlpjoe
Last active January 31, 2018 06:37
Show Gist options
  • Select an option

  • Save nlpjoe/4220f7ae42af01f1711ec8527e7f321d to your computer and use it in GitHub Desktop.

Select an option

Save nlpjoe/4220f7ae42af01f1711ec8527e7f321d to your computer and use it in GitHub Desktop.
[isASCII.py]#python

How to check if a string in Python is in ASCII?

Python 3 way:

isascii = lambda s: len(s) == len(s.encode())

Since ascii characters can be encoded using only 1 byte, so any ascii characters length will be true to its size after encoded to bytes; whereas other non-ascii characters will be encoded to 2 bytes or 3 bytes accordingly which will increase their sizes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment