Chapter 21. Print Formatting and Strings

 

Waaaayyyy back in chapter 1, you learned about the print statement. It was the first command we ever used in Python. We’ve also seen (in chapter 5) that you can put a comma at the end of a print statement to make Python keep printing the next thing on the same line. We used that to make prompts for raw_input(), until we learned the shortcut of putting the prompt right in the raw_input() function.

In this chapter, we’re going to look at print formatting—ways to make your program’s output look the way you want it to. We’ll look at things like

  • starting new lines (and when you should do that).
  • spacing things out horizontally (and lining things up in columns).
  • printing variables in the middle of a string.
  • formatting numbers in integer, decimal, or E-notation format, and setting how many decimal places they should have.

We’ll also learn about some of Python’s built-in methods for working with strings. These methods can do things like

.  splitting strings into smaller parts.

.  joining strings together.

.  searching for strings.

.  searching within strings.

.  removing parts of strings.

.  changing case (uppercase and lowercase).

All of these things will be useful for text-mode (non-GUI) programs, and most of them will find their way into GUIs and game programs as well. There’s a lot more Python can do with print formatting, but this should be all you will need for 99 percent of your programs.

New lines

Horizontal spacing—tabs

Inserting variables in strings

Number formatting

Strings ’n’ things

What did you learn?

Test your knowledge

Try it out