Compute with Words

The computer can also compute with words, or more accurately, with strings which are sequences of characters. We can create a string by typing characters between a pair of single ('Hi'), double ("Hi"), or triple quotes (‘’‘Hi’‘’). We can “compute” with strings using some of the same basic arithmetic operators – they just mean something different here. Here we generate silly song lyrics by using + to combine (append) two strings and * to repeat strings.

Underneath the program below, to the right of the Run button run button, you’ll see the button to open the audio tour for this program: audio tour button. Click on that button and then click on “Line-by-line Tour” to hear the audio tour. You can use the provided buttons to pause, play, jump ahead, or go back.

A string can also be asked to return a new string that is changed in some way from the original string. In the example below, we’ll take a string in all-caps and turn it into a nicely capitalized sentence. This example uses dot-notation (sentence.lower()) which is the way to tell a string how we want it to change.

    csp-1-4-1: What would the following code print?

    first = "Hi"
    next = "There"
    print ((first + next) * 2)
    
  • Hi There
  • When you add strings together you copy the second string right after the first, without any added space
  • HiThere
  • Remember that * 2 repeats two copies of the same string
  • Hi There Hi There
  • Adding strings together and repeating them doesn't add spaces between the strings
  • HiThereHiThere
  • Strings are added together without adding any space and they are repeated without adding a space
  • HiThere2
  • The * 2 repeats the string two times

Note

Discuss topics in this section with classmates.

Show Comments
Next Section - Compute with Turtles