10/9/13

Strings are sequences of characters


In [10]:
word = 'computer'
#print first letter of word
print word[0]
print word[1]
print word[7]
print word[-1]
print word[-2]
print word[1:5]
print word[3:-1]
print word[1:-2]
print word[3:]
print word[:4]


c
o
r
r
e
ompu
pute
omput
puter
comp

In [11]:
print "The length of word is", len(word)


The length of word is 8

In [12]:
word = raw_input("Please type a word: ")
print "The word you entered is", len(word), "characters long!"


Please type a word: fork
The word you entered is 4 characters long!

In [15]:
#take a string from the user
#print out each character individually
word = raw_input("Please give me a word: ")
count = len(word)
x = 0
while x < count:
    print word[x]
    x = x + 1


Please give me a word: iphone
i
p
h
o
n
e

In [17]:
word = raw_input("Please give me a word: ")
for character in word:
    print character


Please give me a word: iphone
i
p
h
o
n
e

In [19]:
word = raw_input("Please give me a word: ")
for character in word:
    print character
    if character == 'g':
        break


Please give me a word: goose
g

Strings are immutable!

You cannot change the value of a string.


In [20]:
word = 'fluffy'
word[0] = 'x'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-840d4977a1b7> in <module>()
      1 word = 'fluffy'
----> 2 word[0] = 'x'

TypeError: 'str' object does not support item assignment

In [21]:
word = 'bob'
word = 'B' + word[1:]
print word


Bob

Searching inside strings


In [22]:
def find(word, letter):
    index = 0
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

print find( "puppy dog", "y" )


4

In [25]:
phrase = "puppy dog"
space = find( phrase, " " )
print phrase[:space]
print phrase[space+1:]


puppy
dog

In [30]:
def find(word, letter, index):
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

print find( "puppy dog", "y", 5 )


-1

String methods


In [31]:
word = "banana"
print word.upper()


BANANA

In [32]:
print word.find('a')


1

In [33]:
print "dog".upper()


DOG

In [ ]: