2 ways to get the size of a string in Python (in bytes)

Updated: June 1, 2023 By: Goodman Post a comment

This concise, straight-to-the-point article will show you 2 different ways to get the size (in bytes) of a string in Python. There’s no time to waste; let’s get started!

Using the encode() method and the len() function

Here’re the steps you can follow:

  1. Encode your string into bytes using the encode() method. You can specify the encoding as an argument, such as encode('utf-8') or encode('ascii'). This will return a bytes object that represents your string in the given encoding.
  2. Use the len() function to get the number of bytes in the resulting bytes object.

Code example:

string = "Welcome to Sling Academy!"
encoded_bytes = string.encode("utf-8")
size_in_bytes = len(encoded_bytes)
print(f"Size of string: {size_in_bytes} bytes")

Output:

Size of string: 25 bytes

This approach gives you the actual byte size of the string. It is the best option for you.

Using sys.getsizeof()

The sys.getsizeof() function provides the size of the input string object in memory, including overhead. Because the result you get may include additional overhead, it may not reflect the actual byte size of the string. Therefore, we have to subtract the result for the size of an empty string returned by sys.getsizeof().

The main points of this approach are:

  1. Import the sys module.
  2. Use the sys.getsizeof() function to get the size of the string object.
  3. Subtract the size of an empty string to get the size of the string in bytes.

Code example:

import sys

string = "Welcome to Sling Academy!"
size_in_bytes = sys.getsizeof(string) - sys.getsizeof("")
print(f"Size of string: {size_in_bytes} bytes")

Output:

Size of string: 25 bytes

That’s it. Happy coding!