Help and Print

Help

If you want to find out about more string methods, you can use the help function.

You can use help on a string object or on the str object.

>>> help(type(name))
>>> help(str)

You can also use help to find out more about a specific method:

>>> help(str.format)
>>> help("my string".format)

Print

So when we type an expression at the REPL, the value returned will be printed.

Once we start making Python programs, we’ll need to use the print function to print out strings.

When we use the print function it will print our strings the way humans like to see them. The quotes surrounding our strings will not be shown and special characters will be converted appropriately.

To print a string over two lines we can use \n:

>>> print("Hello\nWorld!")
Hello
World!

We can also make multi-line strings using triple-quoted strings:

>>> greeting = """Hello
... World!"""
>>> print(greeting)
Hello
World!

Note that the REPL recognizes that the line greeting = """Hello is incomplete and changes the prompt to three dots to let you know that you need to continue before Python can interpret the command.

Python allows multiplication of strings and integers to make repeated strings:

>>> print("Hello! " * 10)
Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello!
>>> verse = """This is the song that never ends
... It just goes on and on my friend
... Some people started singing it not knowing what it was,
... And they'll continue singing it forever just because...
...
... """
>>> song = verse * 5
>>> print(song)
# ...

Help Discovery Exercises

Count occurrence of word

  1. Make a multi-line string that contains the text of the declaration of independence (hint: copy-paste it from the file declaration-of-independence.txt that you downloaded to your python_class directory)
  2. Count the number of times the phrase “people” appears in the declaration (hint: dig through the string documentation)

Format decimal places

  1. Make a variable cost and set it to 5.5
  2. Format a string that contains a dollar sign and the value of the cost variable, formatted to two contain decimal places (“$5.50”)

Use silly case

Alter the declaration of independence to make every word consist of a lower case character followed by all uppercase characters

Count

Count the number of words in the declaration of independence.

Count the number of lines in the declaration of independence.