Strings
Let's talk about strings. What happens if we just type in the text:
>>> Trey
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'
String Exercises
Time to explore strings!
How many strings can you add together? Try concatenating 3 or 4 strings together and see if it works.
What happens here:
"2" + "3"
? What do you expect will happen? And what actually happened? Why?Take a guess at what
"2" + 2
will do. Then try it out. Now take a guess at what"2" * 2
will do. Try that out too.What do you think will happen when you open a string with a single quote and close it with a double quote? What's your guess? Now try it out!
Bonus
When we added a string and an integer it gave us an error. How could we fix this?
How could you make a string all uppercase? Or all lowercase? See string methods in Python for hints.