By John Paul Mueller

Python provides myriad ways to output information. In fact, the number of ways would amaze you. Real-world printing can become complex, so you need to know a few additional printing techniques to get you started. Using these techniques is actually a lot easier if you play with them as you go along.

  1. 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 the print() method one item at a time. The sep argument tells how to separate each of the printed outputs, relying on a newline character in this case.

  2. Click Run Cell.

    Python outputs the list one item at a time.

    Python splat operator
    Using the splat operator can make your code significantly smaller.
  3. 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 Python
    String functions let you easily format your output in specific ways.
  4. Type the following code into the notebook and click Run Cell.


    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 of Colors. 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.

  5. 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).

    format function Python
    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.