Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/00-Python Object and Data Structure Basics/03-Print Formatting with Strings.ipynb
Views: 648
String Formatting
String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation. As a quick comparison, consider:
There are three ways to perform string formatting.
The oldest method involves placeholders using the modulo
%
character.An improved technique uses the
.format()
string method.The newest method, introduced with Python 3.6, uses formatted string literals, called f-strings.
Since you will likely encounter all three versions in someone else's code, we describe each of them here.
Formatting with placeholders
You can use %s
to inject strings into your print statements. The modulo %
is referred to as a "string formatting operator".
You can pass multiple items by placing them inside a tuple after the %
operator.
You can also pass variable names:
Format conversion methods.
It should be noted that two methods %s
and %r
convert any python object to a string using two separate methods: str()
and repr()
. We will learn more about these functions later on in the course, but you should note that %r
and repr()
deliver the string representation of the object, including quotation marks and any escape characters.
As another example, \t
inserts a tab into a string.
The %s
operator converts whatever it sees into a string, including integers and floats. The %d
operator converts numbers to integers first, without rounding. Note the difference below:
Padding and Precision of Floating Point Numbers
Floating point numbers use the format %5.2f
. Here, 5
would be the minimum number of characters the string should contain; these may be padded with whitespace if the entire number does not have this many digits. Next to this, .2f
stands for how many numbers to show past the decimal point. Let's see some examples:
For more information on string formatting with placeholders visit https://docs.python.org/3/library/stdtypes.html#old-string-formatting
Multiple Formatting
Nothing prohibits using more than one conversion tool in the same print statement:
Formatting with the .format()
method
A better way to format objects into your strings for print statements is with the string .format()
method. The syntax is:
For example:
The .format() method has several advantages over the %s placeholder method:
1. Inserted objects can be called by index position:
2. Inserted objects can be assigned keywords:
3. Inserted objects can be reused, avoiding duplication:
Alignment, padding and precision with .format()
Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more
By default, .format()
aligns text to the left, numbers to the right. You can pass an optional <
,^
, or >
to set a left, center or right alignment:
You can precede the aligment operator with a padding character
Field widths and float precision are handled in a way similar to placeholders. The following two print statements are equivalent:
Note that there are 5 spaces following the colon, and 5 characters taken up by 13.58, for a total of ten characters.
For more information on the string .format()
method visit https://docs.python.org/3/library/string.html#formatstrings
Formatted String Literals (f-strings)
Introduced in Python 3.6, f-strings offer several benefits over the older .format()
string method described above. For one, you can bring outside variables immediately into to the string rather than pass them as arguments through .format(var)
.
Pass !r
to get the string representation:
Float formatting follows "result: {value:{width}.{precision}}"
Where with the .format()
method you might see {value:10.4f}
, with f-strings this can become {value:{10}.{6}}
Note that with f-strings, precision refers to the total number of digits, not just those following the decimal. This fits more closely with scientific notation and statistical analysis. Unfortunately, f-strings do not pad to the right of the decimal, even if precision allows it:
If this becomes important, you can always use .format()
method syntax inside an f-string:
For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings
That is the basics of string formatting!