Special Python String Formatting in Logging and Unit Conversion
Learn special Python string formatting in different cases
--
In this article, some special cases of string formatting will be discussed. Both the old and new styles of string formatting will be introduced. While f-string formatting is recommended to be used in most cases now, the old percent sign formatting and str.format()
still have their advantages in some special cases. After that, the pint library will be introduced which is very convenient to convert values to different units. pint uses a very special and interesting way to format units, as you will see soon.
Percent sign string formating.
If you have been using Python since the 2.x version, you should be very familiar with this type of string formatting. This was once the only way to format strings in Python. The basic syntax for percent sign string formating is:
Here %s
means a string value is required and %d
an integer number.
We can use mapping keys in the percent sign formatting style as well, the syntax is:
As we see, the mapping keys are put in parentheses between the percent sign and the type identifier. The values are passed in as a dictionary with the mapping keys as the keys. This type of styling is very common when you run raw SQL queries with SQLAlchemy, which is a very popular open-source SQL toolkit and object-relational mapper for Python, for example: