Byte size of string

OSCC · Python, String · Nov 2, 2020

Returns the length of a string in bytes.

  • Use str.encode() to encode the given string and return its length.
def byte_size(s):
  return len(s.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11

Recommended snippets

  • Pad string

    Python, String

    Pads a string on both sides with the specified character, if it's shorter than the specified length.

  • Pad number

    Python, String

    Pads a given number to the specified length.

  • Hex to RGB

    Python, String

    Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.