How to Get the Size of a String in Python?

Rate this post

Problem Formulation: Given a string my_string. Find the number of characters of the string! For example, the string `"what is my length?"` must yield integer `18` because it has 18 characters.

Here are three examples of our desired outputs:

```my_string = "what is my length?"
# Desired output: 18

my_string = "hello"
# Desired output: 5

my_string = ""
# Desired output: 0```

Solution: Before we dive into alternatives, here’s the quick answer to this question.

To get the number of characters of a Python string, call Python’s built-in function `len(string)`. For example, `len('hello')` returns 5 and `len('')` returns 0. Because the `len()` function is a Python built-in function, you don’t need to import any library. Pass any iterable into it to find the number of elements. As a string is an iterable of characters, `len()` returns the number of characters on a string value.

Here are the three examples:

```my_string = "what is my length?"
print(len(my_string))
# 18

my_string = "hello"
print(len(my_string))
# 5

my_string = ""
print(len(my_string))
# 0
```

Here’s an introduction into Python’s built-in `len()` function:

Just for comprehensibility, I want to address a variant of this question: How to get the size of a string in Python:

How to Get the Number of Bytes Needed to Encode a String in Python?

To get the number of bytes needed to encode a string in Python, import the `sys` module and call function `sys.getsizeof(string)` on the string. For example, `sys.getsizeof('hello')` returns 54 because it requires 54 bytes to encode the five characters.

Here’s a basic example where you count the number of bytes of the string `'hello'`:

```import sys
print(sys.getsizeof('hello'))
# 54```

Let’s examine how this number changes when applying it on shorter and shorter strings:

```print(sys.getsizeof('ello'))
# 53

print(sys.getsizeof('llo'))
# 52

print(sys.getsizeof('lo'))
# 51

print(sys.getsizeof('o'))
# 50

print(sys.getsizeof(''))
# 49```

You can see that even the empty string requires 49 bytes on my computer for housekeeping! Note that this may be different on your computer with another Python version.