Adding & Multiplying Strings
There's many ways to manipulate strings, and we'll talk about some of them in a future lesson.
For now, addition and multiplication are two neat things you can do with strings.
For now, addition and multiplication are two neat things you can do with strings.
Adding Strings Together
Python allows you to add strings together:
In Python's world, adding strings glues them together, no matter what the strings' value. Notice that if you want spaces in between the different string-words, you've got to add them yourself; Python doesn't assume each string you're adding is its own word.
Here's another example of Python's way of "gluing" strings together:
Here's another example of Python's way of "gluing" strings together:
This can be confusing, because 1 + 7 = 8, but '1' + '7' = '17'. (Adding together string-numbers, rather than number-numbers, ends up being a common source of bugs in programs!)
Subtraction?
Nah. Subtracting strings doesn't work.
Multiplying Strings By Numbers
Python also allows you to multiply strings by numbers:
Even if the strings are stringified numbers, Python still just duplicates them – when we're dealing with strings, no math is preformed.
Division?
Division with strings doesn't work, either. (Which is kind of a relief, since it's hard to think about what it would mean to divide a string.)
Challenge!
- Use string multiplication to say "hi!" ten times
- Use string addition to wish goodbye to this section; you'll want to write a line of code that'll print something like "Goodbye string addition and multiplication!"