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:
- Encode your string into bytes using the
encode()
method. You can specify the encoding as an argument, such asencode('utf-8')
orencode('ascii')
. This will return a bytes object that represents your string in the given encoding. - 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:
- Import the
sys
module. - Use the
sys.getsizeof()
function to get the size of the string object. - 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!