Determining String Byte Size

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a string is a sequence of characters. Each character in a string takes up a certain amount of memory. The amount of memory taken up by a string is known as its byte size. In this challenge, you will write a function that takes a string as input and returns its byte size.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13593{{"`Determining String Byte Size`"}} python/function_definition -.-> lab-13593{{"`Determining String Byte Size`"}} python/build_in_functions -.-> lab-13593{{"`Determining String Byte Size`"}} end

Byte Size of String

Write a function byte_size(s) that takes a string s as input and returns its byte size. The byte size of a string is the number of bytes required to store the string in memory. To calculate the byte size of a string, you need to encode the string using a specific encoding scheme. In this lab, you will use the UTF-8 encoding scheme.

To calculate the byte size of a string, you can follow these steps:

  1. Encode the string using the UTF-8 encoding scheme.
  2. Get the length of the encoded string.

Your function should return the length of the encoded string.

def byte_size(s):
  return len(s.encode('utf-8'))
byte_size('😀') ## 4
byte_size('Hello World') ## 11

Summary

In this challenge, you learned how to calculate the byte size of a string in Python. You wrote a function that takes a string as input and returns its byte size by encoding the string using the UTF-8 encoding scheme and getting the length of the encoded string.

Other Python Tutorials you may like