Monday, May 2, 2016

Lesson 3 in Codeskulptor

We'll learn a bit more about strings in this lesson.
Strings have some methods/functions that you can call like upper() and lower() and others too (if you look them up).
upper() returns the string in uppercase
lower() returns the string in lowercase
you call them by adding a period (.) and calling the method like for example
print "Hello".upper()
which will print out HELLO
print "Hello".lower()
which will print out hello
try it and see.
You can declare a variable like
myname = "Joe" and then call the method like
print myname.upper()
or if you want to set myname to capitals you can do
myname = myname.upper()

Because a string is a sequence of characters they act like lists (I say like because you can perform list functions on them you'll learn about lists later) but you can refer to letter or letters of the string by using the square bracket notations.  For example if you wanted the first character of myname variable
you can refer to it by using
myname[0]
The zero is used because in Python indexes start at 0 instead of 1, so to get the 2nd character you would use myname[1] Also with the square bracket notation. You can get many letters at once by specifying an index to start from, then a colon, then an index to stop at. For example if we wanted the 2nd letter and the 3rd letter of my name we'd use
myname[1:3]
this would return OE If you want to start at the second letter and right to the end of the string doesn't matter how long the string is you just leave the 2nd index(the number after the colon) blank like
myname[1:]
which would also return OE
If you wanted every second letter starting with the first letter you can specify another colon and another number, this number is a step count. for example
myname[0:3:2]
which would return JE or if you want the every 2nd letter starting with the first letter of any string of any length you can leave out the first index and second index and just specify step count like
myname[::2]
There's a trick that i learned to get the string in reverse order which is not to specify first and second index and just specify step of -1 like
myname[::-1]
which would return EOJ
What if you wanted to get every second letter start with the second letter/character of a string like "Hello, how are you?"
You can do something like this
"Hello, How are you?"[1::2]
which will return el,Hwaeyu

Okay I think we know enough about strings for now.
That's it for third lesson
Lesson reference: http://www.codeskulptor.org/#user41_zPETMePp1x_2.py
Lessons Index