Byte Size of String | Challenge

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-13061{{"`Byte Size of String | Challenge`"}} python/function_definition -.-> lab-13061{{"`Byte Size of String | Challenge`"}} python/build_in_functions -.-> lab-13061{{"`Byte Size of String | Challenge`"}} end

Byte Size of String

Problem

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 challenge, 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.

Example

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

In the example above, the byte size of the string '😀' is 4 because it requires 4 bytes to store the UTF-8 encoded version of the string in memory. The byte size of the string 'Hello World' is 11 because it requires 11 bytes to store the UTF-8 encoded version of the string in memory.

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