BackOutputs and Formatting in Python
Study Guide - Smart Notes
Tailored notes based on your materials, expanded with key definitions, examples, and context.
Outputs and Formatting
Introduction
In Python programming, controlling the appearance of output is essential for creating readable and professional-looking results. This section covers the use of the format method, field width specification, justification, and escape sequences to manage output formatting.
Format Method
Overview of the format() Method
format() is a string method used to insert values into a string with specific formatting.
Curly braces {} act as placeholders within the string, which are replaced by the arguments passed to format().
Formatting options allow control over number display, alignment, width, and precision.
Number Formatting with format()
The format() method can be used to control how numbers are displayed, including integer formatting, thousands separators, rounding, and percentage display.
Code | Outcome | Comment |
|---|---|---|
"{0:10d}".format(12345678) | 12345678 | number is an integer |
"{0:10,d}".format(12345678) | 12,345,678 | thousands separator |
"{0:10.2f}".format(1234.5678) | 1234.57 | rounded |
"{0:10,.2f}".format(1234.5678) | 1,234.57 | rounded and separated |
"{0:10,.3f}".format(1234.5678) | 1,234.568 | rounded and separated |
"{0:10.2%}".format(12.345678) | 1234.57% | changed to % and rounded |
"{0:10,.3%}".format(12.34569) | 1,234.569% | %, rounded, separated |
Example: Formatting with Curly Brackets
Curly brackets can include formatting codes to specify how each value is displayed.
Example code:
"The area of {0:s} is {1:,d} square miles.".format("Texas", 268820) "The population of {0:s} is {1:.2%} of the U.S. population.".format("Texas", 26438000 / 309000000)
Output:
The area of Texas is 268,820 square miles. The population of Texas is 8.56% of the U.S. population.
Justifying Output in a Field
Field Width and Justification
When displaying tabular data, it is often necessary to align text and numbers in columns of fixed width. The format() method and string methods like ljust(), rjust(), and center() are used for this purpose.
ljust(n): Left-justifies the string in a field of width n.
rjust(n): Right-justifies the string in a field of width n.
center(n): Centers the string in a field of width n.
Example: Tabular Output
Consider the following table of baseball players and home runs:
Rank | Player | HR |
|---|---|---|
1 | Barry Bonds | 762 |
2 | Hank Aaron | 755 |
3 | Babe Ruth | 714 |
To align this data, use:
"{0:^5s}{1:3s}".format("Rank", "Player", "HR") "{0:^5n}{1:3n}".format(1, "Barry Bonds", 762) "{0:^5n}{1:3n}".format(2, "Hank Aaron", 755) "{0:^5n}{1:3n}".format(3, "Babe Ruth", 714)
Specifying Field Width with format()
For strings: "{0:<ws}".format(str1) (left-justify), "{0:^ws}".format(str1) (center), "{0:>ws}".format(str1) (right-justify)
For numbers: "{0:<wm}".format(num) (left-justify), "{0:^wm}".format(num) (center), "{0:>wm}".format(num) (right-justify)
Escape Sequences
Definition and Usage
Escape sequences are special character combinations starting with a backslash (\) that represent non-printable or special characters in strings.
\t: Horizontal tab
\n: Newline
\': Single quote
\": Double quote
\\: Backslash
Examples of Escape Sequences
print("a\tb\te") # Output: a b e print("Nudge, \tnudge, \nwink, \twink.") # Output: # Nudge, nudge, # wink, twink.
The expandtabs() method can change the default tab size.
Escape sequences are counted as a single character in string length calculations.
Removing Newlines and Spaces
The rstrip() method removes trailing whitespace and newline characters from the end of a string.
When using int(), float(), or eval() on a string, trailing whitespace and escape sequences are ignored.
Arguments in print()
sep and end Arguments
sep: Specifies the separator between multiple values in a print statement.
end: Specifies what is printed at the end of the print statement (default is newline).
print("Hello", "World!", sep="\t") # Output: Hello World! print("tic", "tac", "toe", sep="-") # Output: tic-tac-toe print("Hello", end=" ") print("World!") # Output: Hello World!
Comments and Additional Notes
When using format(), the default justification for strings is left-justified unless specified otherwise.
Placeholders in format() can be abbreviated (e.g., {0:s} can be written as {0}).
Common error: using a forward slash (/) instead of a backslash (\) for escape sequences.
Summary Table: String Justification Methods
Method | Description | Example |
|---|---|---|
ljust(n) | Left-justify in width n | "abc".ljust(5) → "abc " |
rjust(n) | Right-justify in width n | "abc".rjust(5) → " abc" |
center(n) | Center in width n | "abc".center(5) → " abc " |
Additional info: The notes also mention that if a string is longer than the allocated width, the entire string is displayed without truncation, and the field width is ignored.