Page 41 - Programming the Raspberry Pi Getting Started with Python
P. 41
4
Strings, Lists, and Dictionaries
This chapter could have had “and Functions” added to its title, but it was already long enough. In
this chapter, you will first explore and play with the various ways of representing data and adding
some structure to your programs in Python. You will then put everything you learned together into the
simple game of Hangman, where you have to guess a word chosen at random by asking whether that
word contains a particular letter.
The chapter ends with a reference section that tells you all you need to know about the most useful
built-in functions for math, strings, lists, and dictionaries.
String Theory
No, this is not the Physics kind of String Theory. In programming, a string is a sequence of characters
you use in your program. In Python, to make a variable that contains a string, you can just use the
regular = operator to make the assignment, but rather than assigning the variable a number value, you
assign it a string value by enclosing that value in single quotes, like this:
If you want to see the contents of a variable, you can do so either by entering just the variable name
into the Python Shell or by using the print command, just as we did with variables that contain a
number:
There is a subtle difference between the results of each of these methods. If you just enter the
variable name, Python puts single quotes around it so that you can tell it is a string. On the other hand,
when you use print, Python just prints the value.
NOTE You can also use double quotes to define a string, but the convention is to use single quotes
unless you have a reason for using double quotes (for example, if the string you want to create has
an apostrophe in it).
You can find out how many characters a string has in it by doing this:
You can find the character at a particular place in the string like so:
Two things to notice here: first, the use of square brackets rather than the parentheses that are used
for parameters and, second, that the positions start at 0 and not 1. To find the first letter of the string,
you need to do the following:
If you put a number in that is too big for the length of the string, you will see this:
This is an error, and it’s Python’s way of telling us that we have done something wrong. More
specifically, the “string index out of range” part of the message tells us that we have tried to access
something that we can’t. In this case, that’s element 100 of a string that is only 24 characters long.