Python Convert String to CSV File

Problem Formulation Given a Python string: πŸ’¬ Question: How to convert the string to a CSV file in Python? The desired output is the CSV file: ‘my_file.csv’: a,b,c 1,2,3 9,8,7 Simple Vanilla Python Solution To convert a multi-line string with comma-separated values to a CSV file in Python, simply write the string in a file … Read more

How to Replace Whitespaces with Underscores

Problem Formulation and Solution Overview In this article, you’ll learn how to replace whitespaces with underscores in Python. To make it more fun, we have the following running scenario: Bryan, an IT Instructor, has given his students a Python coding challenge: Take a famous quote and replace all whitespaces with underscores in four (4) ways: … Read more

How to Fix TypeError: unhashable type: ‘list’

The TypeError: unhashable type: ‘list’ usually occurs when you try to use a list object as a set element or dictionary key and Python internally passes the unhashable list into the hash() function. But as lists are mutable objects, they do not have a fixed hash value. The easiest way to fix this error is … Read more

How to Create High Precision Data Types

Problem Formulation and Solution Overview In this article, you’ll learn how to create high-precision data types in Python. πŸ’‘ Definition: High-precision data types are numeric data types, such as integers, or floats, that use additional memory when complex mathematical calculations require extreme accuracy. πŸ’¬ Question: How would we write Python code to create high-precision data … Read more

CSV to XML – How to Convert in Python?

Problem Formulation Input: You have some data in a CSV file stored in ‘my_file.csv’ where the first row is the header and the remaining rows are values associated to the column names in the header. Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000 Desired Output: You want to store the data in an XML file ‘my_file.xml’ so that each … Read more

How to Skip a Line in Python using \n?

Summary: Python’s newline character \n indicates the end of a line of text. The built-in print() function automatically adds a newline character \n at the end. You can customize this behavior of separating two lines using a single newline character ‘\n’ by changing the default end=’\n’ argument of the print() function to your desired string. … Read more

You Cannot Use Python Regex in startswith(). Do This Instead.

I’m sitting in front of my computer refactoring Python code and have just thought of the following question: Can You Use a Regular Expression with the Python string.startswith() Method? The short answer is no. The string.startswith() method doesn’t allow regular expression inputs. And you don’t need it because regular expressions can already check if a … Read more