We have seen how we could assign numbers to variables. We can also assign strings to variables; for example:
>>> FirstName = "Andre"
>>> LastName = "Roberge"
>>> FullName = FirstName + LastName
>>> print FullName
AndreRoberge
Notice how the "plus sign" (+) is used by Python to combine two strings into one; this operation is called a string concatenation. However, notice how there is no space between the first and last name. We can correct this by adding in between a third string composed of a single space character.
>>> FullName = FirstName + " " + LastName >>> print FullName Andre Roberge
Another way to obtain the same result is to use the %s notation we had used for putting numerical variables inside a string.
>>> name = "%s %s" % (FirstName, LastName) >>> print name Andre Roberge
Finally, we can compare and see if both strings are equal.
>>> print name == FullName
True
Try it on your own!
Sometimes, we only want to use a single character in a string, on a small part of a string (called a substring). To do this, it is useful to learn about slicing.
I will give you three rules to remember, and a hint about the notation, and then give you the result of a whole series of examples that you can try on your own with the Python interpreter. Other than the three rules, I will not give you any other explanation for this section, so you will have to look at it very carefully to completely understand what is going on.
Useful notation: [first:last:step]; all three are optional.
Here are the examples:
>>> alphabet = "abcdefghijklmnopqrstuvwxyz" >>> digits = '0123456789' >>> alphabet[0] 'a' >>> alphabet[1] 'b' >>> alphabet[5] 'f' >>> digits[0] '0' >>> digits[7] '7' >>> digits[-1] '9' >>> digits[-2] '8' >>> alphabet[-3] 'x' >>> digits[0:3] '012' >>> digits[0:4] '0123' >>> digits[0:5] '01234' >>> digits[2:5] '234' >>> alphabet[2:5] 'cde' >>> digits[0:10:2] '02468' >>> digits[0::2] '02468' >>> digits[0::3] '0369' >>> digits[::3] '0369' >>> digits[::-1] '9876543210' >>> digits[::-2] '97531' >>> digits[::-3] '9630' >>> alphabet[:10:2] 'acegi'
Make up your own strings and try a few more examples by yourself!