How to convert an hex number to binary in Python?

Problem We would like to convert an hexadecimal number to a binary number system (or from base 16 to base 2). Let’s assume that we have the following hexadecimal (which represent the integer value 512) Running a simple conversion using the bin() function renders a TypeError exception: TypeError: ‘str’ object cannot be interpreted as an … Read more

How to print line numbers of a file in Python?

Get and print line numbers in a file Use the Python enumerate function to loop through a text or csv file and then, for each line print the line number and the line values. Here’s a simple snippet: Create an Example file Assuming that you have the following multi-line text written into a text file … Read more

How to convert a string to a path object in Python?

String to path object with Pathlib Assume that we have the following string that represents a file location in a Windows operating system. We can check the object type of our string using type: Starting Python 3.4 we are able to use the pathlib library, which is part of the standard library, to easily cast … Read more

How to get yesterday’s datetime in Python and Pandas?

Get yesterday datetime in Python You can get the previous day datetime value in python by following this short procedure: Here’s the code that you can use to print the previous date value in Python: Datetime to string in python The code that we posted above returns a datetime object: This will return datetime.date We … Read more

How to add months to a date time object in Python?

Adding months to a Python date object You can use the dateutil.relativedelta function in order to append an arbitratry number of months to a Python datetime object. The code below adds 2 months to a date: Incrementing a date object in Python – example Our task for today will be to sum an arbitrary number … Read more

How to convert Python list elements to integers?

Cast list elements to int in Python You can easily convert all elements in your Python list from string to int by using a simple list comprehension: Problem We have an array of string elements representing numbers and we would like to convert those to the integer data type so that we can use them … Read more

How to lower case a string and a list in Python?

Change case of Python string and list to lower You can easily lowercase a Python string by using the lower() function. Lists can be converted to lowercase using a list comprehension: Convert a string to lower case Consider the following capitalized Python string that we will be working with along this tutorial Changing the string … Read more