Skip to content

Instantly share code, notes, and snippets.

@dpk
Created February 15, 2015 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpk/d04869e495cc1505e9f7 to your computer and use it in GitHub Desktop.
Save dpk/d04869e495cc1505e9f7 to your computer and use it in GitHub Desktop.
JavaScript length of a string (Python)
# jslen -- find the JavaScript length of a string (Python 3)
#
# Note to Python developers: since you know it as of Python 3.3, it'd
# be nice to have a way to find out in O(1) if a string contains any
# wide characters.
# find the preferred (i.e. faster) byte order
if ''.encode('utf-16') == b'\xFE\xFF':
preferred_encoding = 'utf-16le'
else:
preferred_encoding = 'utf-16be'
def jslen(str):
return len(str.encode(preferred_encoding)) >> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment