Home > python > Python string length

Python string length

Like other programming languages we can find the length & size of a string in python. Python string length can be obtained by using a built-in function len () in python. This function takes the string as a parameter and returns the integer value which is the length of the string. Below is the basic syntax of the python len () function.

len (my_str) # my_str is the string argument and the function will return its length.

This function returns the total number of characters in the string including white spaces and other characters. But it doesn’t count the escape character ‘\’ in the string. So be careful with the escape character in the string.

Python string length Example

Below is the example of finding the length of string in python.

my_str = "Hi, Welcome to codesLehrer.com";

print "Length of the my_str: ", len(my_str)

Output:

Length of the my_str:  30

python string length

It is not over yet. Because sometimes python string can contain Cyrillic symbols. And if we pass that string to the len () function it will not return the exact number of characters in the string.

E.g.

my_str = 'йцы';

print "Length of my_str:  ", len(my_str)

Output:

Length of my_str: 6

This is because the str can use the variable length encoding internally. So, in order to get the exact number of characters you should know the encoding your str object is using. Then you should convert it to Unicode object.

E.g.

my_str = 'йцы';

print "Length of my_str:  ", len(my_str)

Output:

Length of my_str: 3

Tip: Don’t name your string variable as str. Because it shadows the built-in function str ()

Python Size of string

Sometimes we may need to get the size of a string. I.e. the actual string size in bytes in the memory not the number of characters in the string. As python provides different modules to work with. And we can use any of those modules according to our needs. sys (system-specific parameters and functions) is one of those modules which provides us the access to some of the variables that are used by the interpreter and the functions that interact with the interpreter. sys.getsizeof (object) is the function which returns the size of the object in bytes.

Python size of string example

import sys

my_str = "Hi, Welcome to codesLehrer.com !!!";

print "Size of my_str in bytes: ", sys.getsizeof (my_str)

Output:

Size of my_str in bytes:  71

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: