Page 310 - Beginning Programming with Pyth - John Paul Mueller
P. 310

Python outputs the list one item at a time, as shown in Figure 13- 18.
3. TypethefollowingcodeintothenotebookandclickRunCell. 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, as shown in Figure 13-19. Numerous methods of this sort are described at https://docs.python.org/2/library/string.html. Even though they continue to work, Python may stop using them at any time.
4. TypethefollowingcodeintothenotebookandclickRunCell. 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 of Colors. The output is the same as that shown previously in Figure 13-18, even though the approach is different. The point is to use the approach that best suits a particular need.
5. TypethefollowingcodeintothenotebookandclickRunCell. 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) at https://docs.python.org/3/tutorial/inputoutput.html.
FIGURE 13-18: Using the splat operator can make your code significantly smaller.
        


























































































   308   309   310   311   312