HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Byte size of a Python string

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
pythonbytesizestring

Problem

The byte size of a string is the number of bytes required to encode it. This is particularly useful when working with strings that contain special characters or emojis, as they may require more than one byte to encode.
While the len() function returns the number of characters in a string, it doesn't account for the number of bytes required to encode it. To get the byte size of a string, you can use the str.encode() method to encode the string and then return the length of the encoded string.

Solution

def byte_size(s):
  return len(s.encode('utf-8'))

byte_size('😀') # 4
byte_size('Hello World') # 11

Code Snippets

def byte_size(s):
  return len(s.encode('utf-8'))

byte_size('😀') # 4
byte_size('Hello World') # 11

Context

From 30-seconds-of-code: byte-size

Revisions (0)

No revisions yet.