[sac-forum] Paul's Programming 2

In my last message I showed  a bit about how to use strings.  A string is
sequence of zero or more character bounded by quote.  You can use either
single quotes or double quotes, the just have to match to enclose the
string.

>>> a='He said "Hello."'
>>> print a
He said "Hello."
>>>

You can also use the backslash to escape the meaning of a character, like
the quote:

>>> a="He said \"Hello.\""
>>> print a
He said "Hello."
>>>

Not as pretty, but it is useful when you need both quotes in a string.


Last time I also showed some slicing of strings.  You can select a
position in a string using its index.  The first character is accessed as
[0], the last by [-1].  At first glance this is a bit confusing, just
remember positive value go left-to-right and negative values go
right-to-left.  Also, having the index start at zero can be confusing at
first.  As you gain more experience it won't be much of a problem and will
help avoid problems that can occur if sequences started at one.

>>> a='help'
>>> a[-1]
'p'
>>> a[-3]
'e'
>>> a[-4]
'h'
>>> a[3]
'p'
>>>

Now with slicing you use an index similar to [N:M].  The N is the starting
position and M is the position NOT in the slice.  If you leave the
position blank, the entire string at that end is included:

>>> b='Testing'
>>> b[:4]
'Test'
>>> b[4:]
'ing'
>>> b[4:5]
'i'
>>> b[4:4]
''
>>> b[-7:-1]
'Testin'
>>> b[-7:]
'Testing'
>>>

Last time I also showed you how to lowercase a string.

>>> b.lower()
'testing'
>>> b.upper()
'TESTING'
>>> b.upper().lower()
'testing'
>>> b.upper().lower().title()
'Testing'
>>>

Strings are "objects", so have functionality builtin.  To see a list 
string functions type "help(str)".

In the above, the b.upper() created a new string.  Tacking the .lower() to
that used that new string to create a even newer string, this time in
lower case.  The .title() created a string that is equivalent to original
in the variable b.

The indexing will be seen again when we come to lists in my next message.

        -Paul

Other related posts: