Javascript string.length does not equal Python len()

Viewed 279

Imagine the following text entered in an HTML textarea:

123456


7

If one calculates the length of this text via javascript, i.e. string.length, that comes out to 10.

Now if that input's length is measured in python, i.e. via len(string), it is 13.

It does not look 13 to the human eye, but if one runs print repr(string) in python, we get 123456\r\n\r\n\r\n7. That is 13 characters, not 10. For reference, this test was carried out in Ubuntu OS.

Is there any way for python to report the string length via a mechanism that imitates javascript's string.length's result? I.e. in simpler terms, how do I get 10 in python?

I understand I can manually iterate and collapse \r\n into a single character, but I wonder if there is a more robust - even inbuilt - way to do it? In any case, an illustrative example would be great!

1 Answers

You can make use of Regular Expressions which is much more elegant than iterating. Replacing the characters \n and \r by '' does the trick.

Use the re module of python.

import re
x = '123456\r\n\r\n\r\n7'
y = re.sub(r'\r\n','\n',x)
print(len(y)) #Answer will be 10

For further reference, check out the python docs

Related