1.3. 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.
Strings are different than numbers in that they are objects. Objects are complex entities
in code that combine data (like the text that is part of a string) with behaviors - things theobject
can do. To access the behaviors of an object, we use dot-notation. In dot notation, we use a .
(or dot) to describe which behavior of an object we want to make use of.
For example, the program below uses sentence.lower()
to tell the string sentence that we want
it to give us a copy of itself that has been changed to all lower case letters. We then ask the new
string, called better to make a copy of itself where just the first letter is capitalized.
- 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
What would the following code print?
first = "Hi"
next = "There"
print ((first + next) * 2)