How to get the length (size) of a string in Python?

There are several ways to get string length, i.e. size in symbols in Python.

  • The most perfomance efficient is:

my_var = "my test1"
my_var_length = my_var.__len__()
  • Another option is to get length is:

my_var = "my test2"
my_var_length = len(my_var)

len() function is just a built in wrapper to call the __len__() function from above example. Hence, it is a bit slower.

  • If you are lookin to get size of the string in bytes, not in symbols:

the solution is to use built in sys module:


import sys
my_var = "my test3"
my_var_length = sys.getsizeof(my_var)

Leave a Reply