Let’s talk about strings. What happens if we just type in the text:
We get an error.
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Trey' is not defined
Did anyone figure out how to type text at the REPL? We use quotes.
>>> "PyCon is great!" 'PyCon is great!'
Python doesn’t care if we use double or single quotes.
>>> 'PyCon is really great!' 'PyCon is really great!'
Can we add a number to a string?
>>> "PyCon" + 2017 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not int
We get an error telling us the second value needs to be a string, not an integer. We can make it a string by simply surrounding it with quotes. Then we can add them together. This is called concatenation.
>>> "Pycon" + "2017" 'Pycon2017'
Except that looks goofy; we need a space in there. We can do that by adding a space inside either of the strings.
>>> "Pycon " + "2017" 'Pycon 2017'
Your Turn: Strings 🏁¶
Time to explore strings!
Strings and Operators¶
- How many strings can you add together? Is there any limit?
- When we added a string and an integer it gave us an error, unless we put the integer in quotes, making it a string. Is there any other operator that will work with a string?
- What happens here:
"2" + "3"?
- What happens when you open a string with a single quote and close it with a double quote?
- How many different ways can you mix double and single quotes in a string?
Read the Python Documentation to find ways to make a string a) all upper case b) all lower case, and c) in title case.
These are called “string methods”. For the moment you don’t need to know what they are exactly, but it’s good to know how you use them. To do so, add
.nameofmethod() to whatever you’re trying to change.
Bonus: Multi-line Strings¶
How do you print a multi-line string?