Working with python: strings, if, loops.

Alan Robinson, Spring 2004

>>>
>>> str = 'hello'
>>> str[0]
'h'
>>> str[1]
'e'
>>> len(str)
5
>>> str(len(str)/2)












Traceback (most recent call last):
  File "<pyshell#51>", line 1, in -toplevel-
    str(len(str)/2)
TypeError: 'str' object is not callable


>>> str[len(str)/2]













'l'
>>> str[len(str)]













Traceback (most recent call last):
  File "<pyshell#53>", line 1, in -toplevel-
    str[len(str)]
IndexError: string index out of range



>>> str[len(str)-1]
'o'

>>> if str[0] == 'h':
    print 'yes'


















yes
>>> if str[2] == 'e':
    print 'yay'
else:
    print 'sad'





















sad
>>> pos = 0
>>> while pos < 10:
    print pos













0
0
0
0
0
..... [many more here]
Traceback (most recent call last):
  File "<pyshell#68>", line 2, in -toplevel-
    print pos
KeyboardInterrupt

>>> while pos < 10:
    print pos
    pos = pos + 1















0
1
2
3
4
5
6
7
8
9
>>> pos = 1
>>> while pos < len(str):
    print 'at location ',pos, ', you will find:'
    print str[pos]












at location  1 , you will find:
e
at location  1 , you will find:
e
at location  1 , you will find:
e
at location  1 , you will find:
e
[..... oops]
Traceback (most recent call last):
  File "<pyshell#78>", line 3, in -toplevel-
    print str[pos]
KeyboardInterrupt





>>> pos = 1
>>> while pos < len(str):
    print 'at location ',pos, ', you will find:'
    print str[pos]
    pos = pos + 1

at location  1 , you will find:
e
at location  2 , you will find:
l
at location  3 , you will find:
l
at location  4 , you will find:
o


>>> loc = 0
>>> while loc < len(str):
    if str[loc] != 'l':
        print str[loc]
    loc = loc + 1











h
e
o
>>>


>>> loc = 0
>>> output = ''
>>> while loc < len(str):
    if str[loc] != 'l':
        output = output + str[loc]
    loc = loc + 1

>>> print (output)
heo
>>>