Tuesday, March 8, 2011

Mar. 8

To re-enforce what I've learned on string slices. An example to help me out is:
>>>s = "Andrew"
>>>print s[:]
Andrew
>>>print s[1:2]
n
>>>print s[1:5]
ndre
>>>print s[:-1]
Andre
>>>print s[-1:]
w
And so on......
This technique is really easy to understand. I just had to keep in mind the basic principle that instead of starting to count at one, you start at zero.
With immutable strings, the following program is easy to understand.

>>> greeting = "Hello, world!"
>>> newGreeting = 'J' + greeting[1:]
>>> print newGreeting
Jello, world!
When you want to change the out put of "Hello, world!" to "Jello, world!" all you'd do like the program shows is put new before your variable, then in order to change the letter of the text you'd have to put the exact point to change. Like it says to change from greeting change it would print everything after the first letter, which is H. The [1:] would print every other letter after the H, so then when  you add the 'J' you get the output of "Jello, world!" But if i first started out with trying to change the first word on in greeting by just asking for greeting[0] = 'J' then id get the error of : TypeError: 'str' object does not support item assignment.

1 comment:

  1. Two things:

    1. The "new" in front of "newGreeting" is arbitrary. "foo_greeting" or "cheesecake" would work just as well. It's just a new name.

    2. The Python style guidelines suggest "new_greeting" as a preferred name to "newGreeting". "newGreeting" is the Java way of naming it. I'll fix that in the book as soon as I can.

    ReplyDelete