Page 42 - Programming the Raspberry Pi Getting Started with Python
P. 42

You can chop lumps out of a big string into a smaller string, like this:



             The first number within the brackets is the starting position for the string we want to chop out, and
          the second number is not, as you might expect, the position of the last character you want, but rather

          the last character plus 1.
             As  an  experiment,  try  and  chop  out  the  word raspberry  from  the  title. If you do not specify the
          second number, it will default to the end of the string:



             Similarly, if you do not specify the first number, it defaults to 0.
             Finally, you can also join strings together by using + operator. Here’s an example:




          Lists

          Earlier in the book when you were experimenting with numbers, a variable could only hold a single
          number. Sometimes,  however,  it  is  useful  for  a  variable  to  hold  a  list  of  numbers  or  strings,  or  a
          mixture of both—or even a list of lists. Figure 4-1 will help you to visualize what is going on when a
          variable is a list.






















          Figure 4-1   An array
             Lists  behave  rather  like  strings. After all, a string is a list of characters. The  following  example
          shows you how to make a list. Notice how len works on lists as well as strings:





             Square brackets are used to indicate a list, and just like with strings we can use square brackets to

          find an individual element of a list or to make a shorter list from a bigger one:







             What’s more, you can use = to assign a new value to one of the items in the list, like this:






             This changes the first element of the list (element 0) from 123 to just 1.
             As with strings, you can join lists together using the + operator:
   37   38   39   40   41   42   43   44   45   46   47