Table of Contents
Python String Length
When we call len() function with string object as an argument, internally it calls
__len__() function of string object.
The length of the string is the characters required to write the string. It’s not the memory size required by the Python to store the string object.
Let’s look at some simple examples to print string length.
Copys = 'abc' print(len(s)) # 3
We can use __len__() function also to get the length of the string.
Copyprint(str.__len__('ABC')) # 3 print('abc'.__len__()) # 3
Python String Length having special characters
Copys = 'AåB∫Cç' print(len(s)) # 6
Each Unicode character string is counted as a single string.
Python String Length having newline, tabs, whitespaces, escape characters
Copys = ' A ' print(len(s)) # 5 s = 'A\t\t' print(len(s)) # 3 s = 'A\n\nB' print(len(s)) # 4 s = 'A\'B' print(len(s)) # 3
Note that leading and trailing whitespaces are also counted towards the length of the string.
Tab and Newline characters are also counted as 1 towards the length of the string.
The last string value is
A'B and hence the length is 3.
Python Raw String Length
Python raw strings treat backslash (\) as literal, so backslash will be counted towards the length of the string.
Copys = r'A\t\t' print(len(s)) # 5