How to Convert an Octal Escape Sequence in Python – And Vice Versa?

This tutorial will show you how to convert an But let’s quickly recap what an octal escape sequence is in the first place! πŸ‘‡ What Is An Octal Escape Sequence?πŸ’‘ An Octal Escape Sequence is a backslash followed by 1-3 octal digits (0-7) such as \150 which encodes the ASCII character ‘h’. Each octal escape … Read more

Format Integer List to Hex String – Six Pythonic Ways

Problem Formulation πŸ’¬ Question: How to create a string of hex digits from a list of integers (0–255) so that each hex digit consists of two digits such as “00”, “01”, …, “fe”, “ff”? Here’s an example input/output pair: In: [0, 1, 2, 3, 255, 254, 253] Out: ‘00010203fffefd’ Method 1: Bytearray The easiest way … Read more

Python getattr() and setattr() Nested

Understanding Python’s setattr() and getattr() Functions Next, you’ll learn about the “normal”, non-nested and non-recursive get and set attribute functions. If you already know them well, there’s no need to read this section and you can skip ahead right to the problem formulation and solution. Let’s start with the setattr() function, followed by getattr(). setattr() … Read more

Python bytes vs bytearray

What’s the Difference Between bytes() and bytearray()? The difference between bytes() and bytearray() is that bytes() returns an immutable and bytearray() returns a mutable object. So you can modify a bytearray but not bytes type. Here’s a minimal example that nicely demonstrates the difference of the two functions: You create two variables a and b. … Read more

How to use range(len()) in Python?

Problem Formulation Have you come across the usage of range(len()) while trying to iterate across all the items of a given iterable? Now, this brings up a couple of questions – (i) Why do we use range(len())? (ii) How do we use range(len())? πŸ“Solution Generally, range(len()) allows you to iterate across a given iterable/sequence to … Read more

Python Print Dictionary Keys Without “dict_keys”

Problem Formulation and Solution Overview If you print dictionary keys using print(dict.keys()), Python returns a dict_keys object, i.e., a view of the dictionary keys. The representation prints the keys enclosed in a weird dict_keys(…) wrapper text, e.g., dict_keys([1, 2, 3]). Here’s an example: There are multiple ways to change the string representation of the keys, … Read more