Python String Format
Introduction
Python string format has been widely used to control variables in the string and format the string in a way that the user prefers. However, in practice, the strings printed out still do not look beautiful for various reasons such as bad text alignment and insufficient free spaces.
In this blog post, I am going to describe the general rule of using Python string format, and how to use it to print beautiful strings to console for machine learning and data science projects.
Basic Python String Format Syntax
Syntax
Although the Python string format syntax could be more complicated, I think the following syntax might be sufficient for most of the projects involving scientific computing.
1 | {id : char_to_fill alignment sign width comma num_decimals data_type} |
Instruction
Token | Optional | Explanation |
---|---|---|
id | Yes | The id of the string format placeholder. |
padding_char | Yes | The character used for filling the padding spaces at the start and the end of the string. If no character is given, empty space will be used. |
alignment | Yes | ^ is align center; < is align left; > is align right. |
sign | Yes | If + is used, + or - would be used for positive and negative values, respectively. |
width | Yes | The width of the whole string. If the width is larger than the length of the string to be print, padding_char will be used. |
comma | Yes | If , is used, large numbers will have commas as separator. |
num_decimals | Yes | The number of decimals for floating numbers. Has to be of format .n where n is an integer. |
data_type | Yes | s is string, f is floating number, d is integer number. |
Example
If we run the following code in Python,
1 | example_line = "|{pi:@^+25,.8f}|".format(pi=314159.26) |
The message printed to the console would be
1 | |@@@@+314,159.26000000@@@@| |
Python String Format for Machine Learning and Data Science
We would use the following Python generator to generate fake machine learning training statistics for illustration.
1 | # Generate fake training statistics |
The following Python code could be used to print the aligned training statistics to console automatically, as long as the variable header_items
, and width
were given.
1 | train_op = gen_func(n=10) |
The aligned training statistics printed out would be
1 | ------------------------------------------------------------ |
Reference
Python String Format