You can format strings in a number of ways using Python. The main emphasis of formatting is to present the string in a form that is both pleasing to the user and easy to understand. Formatting doesn’t mean adding effects in this case, but refers merely to the presentation of the data. For example, the user might want a fixed-point number rather than a decimal number as output.
Python format function str.format is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. Printing in Python 2.7 ¶. In fact, print is a special statement, not a function call. The general form of its syntax is print ,. The square brackets indicates that it’s optional to have additional expressions. The. means that you can have 0 or more of them. If evaluates to a single value.
You have quite a few ways to format strings. However, the focus of most formatting is the format() function. You create a formatting specification as part of the string and then use the format() function to add data to that string. A format specification may be as simple as two curly brackets {} that specify a placeholder for data.
You can number the placeholder to create special effects. For example, {0} would contain the first data element in a string. When the data elements are numbered, you can even repeat them so that the same data appears more than once in the string.
The formatting specification follows a colon. When you want to create just a formatting specification, the curly brackets contain just the colon and whatever formatting you want to use.
For example, {:f} would create a fixed-point number as output. If you want to number the entries, the number that precedes the colon: {0:f} creates a fixed-point number output for data element one. The formatting specification follows this form, with the italicized elements serving as placeholders here:
This specification provides you with the in-depth details, but here’s an overview of what the various entries mean:
fill: Defines the fill character used when displaying data that is too small to fit within the assigned space.
align: Specifies the alignment of data within the display space. You can use these alignments:
<: Left aligned
>: Right aligned
^: Centered
=: Justified
sign: Determines the use of signs for the output:
+: Positive numbers have a plus sign and negative numbers have a minus sign.
-: Negative numbers have a minus sign.
<space>: Positive numbers are preceded by a space and negative numbers have a minus sign.
#: Specifies that the output should use the alternative display format for numbers. For example, hexadecimal numbers will have a 0x prefix added to them.
0: Specifies that the output should be sign aware and padded with zeros as needed to provide consistent output.
width: Determines the full width of the data field (even if the data won’t fit in the space provided).
,: Specifies that numeric data should have commas as a thousands separator.
.precision: Determines the number of characters after the decimal point.
type: Specifies the output type, even if the input type doesn’t match. The types are split into three groups:
String: Use an s or nothing at all to specify a string.
Integer: The integer types are as follows: b (binary); c (character); d (decimal); o (octal); x (hexadecimal with lowercase letters); X (hexadecimal with uppercase letters); and n (locale-sensitive decimal that uses the appropriate characters for the thousands separator).
Floating point: The floating-point types are as follows: e (exponent using a lowercase e as a separator); E (exponent using an uppercase E as a separator); f (lowercase fixed point); F (uppercase fixed point); g (lowercase general format); G (uppercase general format); n (local-sensitive general format that uses the appropriate characters for the decimal and thousands separators); and % (percentage).
The formatting specification elements must appear in the correct order or Python won’t know what to do with them. If you specify the alignment before the fill character, Python displays an error message rather than performing the required formatting. The following steps help you see how the formatting specification works and demonstrate the order you need to follow in using the various formatting specification criteria.
Open a Python File window.
You see an editor in which you can type the example code.
Type the following code into the window — pressing Enter after each line:
The example starts simply with a field formatted as a decimal value. It then adds a thousands separator to the output. The next step is to make the field wider than needed to hold the data and to center the data within the field. Finally, the field has an asterisk added to pad the output.
Of course, there are other data types in the example. The next step is to display the same data in fixed-point format. The example also shows the output in both uppercase and lowercase hexadecimal format. The uppercase output is right aligned and the lowercase output is left aligned.
Finally, the example shows how you can use numbered fields to your advantage. In this case, it creates an interesting string output that repeats one of the input values.
Choose Run→Run Module.
You see a Python Shell window open. The application outputs data in various forms.
# let's say you have four sequences you want to print columnwise, like so: |
19599744 |
92576368 |
66216990 |
75661219 |
# mock some data |
import random asRND |
gen_row =lambda: [ RND.randint(10, 99) for c inrange(3) ] |
# 'data' is a nested list comprised of five rows and three columns |
data = [gen_row() for c inrange(5)] |
# create some column headers |
col_headers = ['col{}'.format(i) for i inrange(1, 4)] |
# print the column headers first |
print('{:^8}{:^8}{:^8}'.format(*col_headers) |
# now print the rows |
for row in |
aligned_row='{:^8}{:^8}{:^8}'.format(*row) |
print(aligned_row) |
# i have not used placeholders in my print statement, eg, {0}, {1}, as of python 3.3 i believe, |
# you can omit them and the sequence is implicit because i have four sets of curly braces and four arguments |
# passed to 'format' |
'' |
{:^8} says (seems more intuitive if i read it backwards: |
{} => create one field |
8 => it will have a width of 8 |
^ => center the data within this field (use '<' for left align and '>' for right align) |
every token inside the curly braces is either |
(i) an index to the sequence passed to 'format', or |
(ii) a format specifier, |
depending on whether it is to the left or right of the colon, |
{index, format specifier} |
'' |
# more format specifiers: |
# to control number formatting (eg, number of places to the right of the decimal to print for floats) eg, |
# the statement below says to print the value for that field with two decimal places |
'{:^8.2f}'.format(v1) |
# but how do you know what order to place these format specifiers? |
# ie, why not |
'{:.2f^8}'# wrong |
# the python docs publish a 'general form for a standard format specifier: |
# http://docs.python.org/2.6/library/string.html#formatstrings |
commented Jun 20, 2018
What's going on in row 21?
won't compile. |