- Type the following code into the notebook — pressing Enter after each line:
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
print(*Colors, sep='\n')
You use a
for
loop to print the individual items. This example takes another approach. It uses the splat (*
) operator, also called the positional expansion operator (and an assortment of other interesting terms), to unpack the list and send each element to theprint()
method one item at a time. Thesep
argument tells how to separate each of the printed outputs, relying on a newline character in this case. - Click Run Cell.
Python outputs the list one item at a time.
Using the splat operator can make your code significantly smaller. - Type the following code into the notebook and click Run Cell."
for Item in Colors: print(Item.rjust(8), sep='/n')
Code doesn't have to appear on multiple lines. This example takes two lines of code and places it on just a single line. However, it also demonstrates the use of the
rjust() method
, which right justifies the string. Numerous methods of this sort are described here. Even though they continue to work, Python may stop using them at any time.String functions let you easily format your output in specific ways. - Type the following code into the notebook and click Run Cell.
print'\n'.join(Colors))
Python provides more than one way to perform any task. In this case, the code uses the
join()
method to join the newline character with each member ofColors
. The output is the same as that shown above, even though the approach is different. The point is to use the approach that best suits a particular need. - Type the following code into the notebook and click Run Cell.
print('First: {0}\nSecond: {1'.format(*Colors))
In this case, the output is formatted in a specific way with accompanying text, and the result doesn't include every member of
Colors
. The{0}
and{1}
entries represent placeholders for the values supplied from*Colors
. Figure 13-20 shows the output. You can read more about this approach (the topic is immense).Use the format() function to obtain specific kinds of output from your application.
This information touches on only some of the common techniques used to format output in Python. There are lots more. The essential goal is to use a technique that's easy to read, works well with all anticipated inputs, and doesn’t paint you into a corner when you’re creating additional output later.