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¶
- Make a multi-line string that contains the text of the declaration of independence (hint: copy-paste it from the file
declaration-of-independence.txtthat you downloaded to yourpython_classdirectory) - Count the number of times the phrase “people” appears in the declaration (hint: dig through the string documentation)
Format decimal places¶
- Make a variable
costand set it to5.5 - Format a string that contains a dollar sign and the value of the
costvariable, 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.