As the students used to say to Mr. Kotter: "Welcome back, welcome back, welcome back." In our previous article we talked some more about how to manipulate strings in Python, leaving off with indexing and slicing. Here, we will pick up again with slicing, using it to “change” the contents of a string.
I say "change" in quotation marks because technically strings are immutable, or in less fancy speak, they are like a hippy's views of the world -- they cannot be changed. Unless of course the 1980s and big business rolls around and those hippies discover the wonderful world of free commerce. You get a job you damn hippy!
Just a side note: hippy is not in my Word dictionary, but Lippy, Tippy, Pippy, and Hippo are for some reason.
Tricking the Computer
I don't know why we have to trick the computer in order to change a string. I mean, why couldn't strings just be changeable? Because computer programmers like to mess with you, that's why, especially the ones that create languages and specifically the ones that create open source languages. They don't make money, so their sole satisfaction is to confound you. And let's face it, that isn't too hard to do.
Here is how we "change" those hippy strings. Note that we will be writing this code at the command prompt of our Python shell.
>>> woodstock='I am a hippy'
>>> wallstreet=woodstock[0:7] + 'yuppie'
>>> print wallstreet
I am a yuppie
Let's have a little more fun with it. In the following example, we will assign the alphabet to a variable named, well, alphabet, then use slicing to print out the coolest name in history. Note that the index number for the string begins with 0, so for instance, a is index 0, b is in index 1, and z is index 25, as opposed to 26.