Skip to content

Instantly share code, notes, and snippets.

@dpk dpk/jslen.py
Created Feb 15, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.