While it is quite fun to use strings to play with kittens, it’s even more fun to use strings to play with Python! (Although far less cute.) A string in programming speak is an ordered series of characters, which is a fancy way of saying “words”. Let’s play with some strings!
If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!
To write a string, take any set of characters and put either double or single quotation marks around it:
1 2 3 4
>>> 'hi' 'hi' >>> "howdy" 'howdy'
To Python, there is no difference between using single quotes (
') and double quotes (
Shift+'), as long as you use the same one for that string. Nobody likes mismatched bookends. (Not sure that’s a good example, as nobody uses bookends to begin with.)
We can also assign strings to a variable, just like numbers!
1 2 3
>>> hi_string = 'hi' >>> hi_string 'hi'
and even add them!
>>> hi_string + 'howdy' 'hihowdy'
Let’s add a space between those two:
>>> hi_string + ' ' + 'howdy' 'hi howdy'
We can even type whole sentences, punctuation and all:
1 2 3
>>> taunt = "Your mother was a hamster and your father smelt of elderberries!" >>> taunt 'Your mother was a hamster and your father smelt of elderberries!'
If we need to use an apostrophe (also known as the single quotation mark,
') in the middle of our sentence, we can either use the double quotation marks:
>>> "It's a wonderful day in the neighborhood." "It's a wonderful day in the neighborhood."
or we can escape the apostrophe with a backslash (
\). This tells the Python interpreter to ignore the special character following it. In this example, we use
>>> 'It\'s a wonderful day in the neighborhood.' "It's a wonderful day in the neighborhood."
You can also include numbers inside your strings:
1 2 3
>>> box_message = "I have 3 boxes." >>> box_message 'I have 3 boxes.'
You can’t, however, add a number to a string. First you must convert the number to a string using the
1 2 3 4 5 6
>>> '1' + '1' # Adding strings '11' >>> 1 + 1 # Adding numbers 2 >>> 'hello' + str(1) # Adding numbers to strings 'hello1'
See? Just as fun as kittens!