How to Convert Hex String to Bytes in Python?

Problem Formulation Given a string in hexadecimal form: How to convert the hex string to a bytes object in Python? Here are a few examples: Hex String Bytes Object ’01’ b’\x01′ ’04’ b’\x04′ ’08’ b’\x08′ ’01 0a’ b’\x01\n’ ’01 02 0e 0f 0f’ b’\x01\x02\x0e\x0f\x0f’ ‘0f 0f’ b’\x0f\x0f’ Hex String to Bytes using bytes.fromhex(hex_string) To convert … Read more

Python | Split String at Position

Summary: You can split a given string at a specific position/index using Python’s string–slicing syntax. Minimal Example: Problem Formulation πŸ’¬Problem: Given a string, how will you split the given string at any given position? Let’s have a look at a couple of examples that demonstrate what the problem asks you to do: β—ˆExample 1 The following … Read more

Python Regex Named Groups

Before we dive into named groups, let’s quickly recap normal capture groups in Python. If you already know normal “unnamed capturing groups” well, feel free to skip the first section and move right away to the next one about named capture groups in Python. πŸ‘‡ What Are Python Regex Groups? A normal Python regex group … Read more

6 Ways to Remove Python List Elements

Problem Formulation and Solution Overview This article will show you how 6 ways to remove List elements in Python. To make it more interesting, we have the following running scenario: Suppose you have a Christmas List containing everyone to buy a gift for. Once a gift is purchased, remove this person from the List. Once … Read more

Python Return Error From Function

Problem Formulation πŸ’¬ Question: How do you write a function that returns a real Python error instead of an “error code” such as -1 or None in case something got wrong? For example, you may want to check the function input arguments for having the correct type or length (in the case of iterable arguments) … Read more

Python | Split String by Whitespace

Summary: Use “given string”.split() to split the given string by whitespace and store each word as an individual item in a list. Minimal Example: Problem Formulation πŸ’¬ Problem: Given a string, How will you split the string into a list of words using whitespace as a separator/delimiter? Let’s understand the problem with the help of a few examples: … Read more

Python Return Integer From Function

Do you need to create a function that returns an integer value but you don’t know how? No worries, in sixty seconds, you’ll know! Go! πŸ”₯πŸ”₯πŸ”₯ A Python function can return any object. To return an integer, use the built-in int() function. Or create your own function with an arbitrary expression within the function body … Read more