Python String Length

Filed Under: Python

Python String length can be determined by using built-in len() function.

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.

s = 'abc'

print(len(s))  # 3

We can use __len__() function also to get the length of the string.

print(str.__len__('ABC'))  # 3
print('abc'.__len__())  # 3

Python String Length having special characters

s = '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

s = '  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.

s = r'A\t\t'
print(len(s))  # 5
You can checkout complete python script and more Python examples from our GitHub Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages