Created
February 15, 2015 18:56
-
-
Save dpk/d04869e495cc1505e9f7 to your computer and use it in GitHub Desktop.
JavaScript length of a string (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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