Thứ Sáu, 14 tháng 2, 2014

06-Strings

A Character Too Far

You will get a python error if you
attempt to index beyond the end
of a string.

So be careful when constructing
index values and slices
>>> zot = 'abc'
>>> print zot[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of
range
>>>
Strings Have Length

There is a built-in function len that
gives us the length of a string
>>> fruit = 'banana'
>>> print len(fruit)
6
0
b
1
a
2
n
3
a
4
n
5
a
Len Function
>>> fruit = 'banana'
>>> x = len(fruit)
>>> print x
6
len()
function
'banana'
(a string)
6
(a number)
A function is some stored
code that we use. A
function takes some input
and produces an output.
Guido wrote this code
Len Function
def len(inp):
blah
blah
for x in y:
blah
blah
A function is some stored
code that we use. A
function takes some input
and produces an output.
>>> fruit = 'banana'
>>> x = len(fruit)
>>> print x
6
'banana'
(a string)
6
(a number)
Looping Through Strings

Using a while statement and
an iteration variable, and the
len function, we can construct
a loop to look at each of the
letters in a string individually
index = 0
while index < len(fruit) :
letter = fruit[index]
print index, letter
index = index + 1
0 b
1 a
2 n
3 a
4 n
5 a
Looping Through Strings

A definite loop using a for
statement is much more
elegant

The iteration variable is
completely taken care of by
the for loop
b
a
n
a
n
a
for letter in fruit :
print letter
Looping Through Strings

A definite loop using a for
statement is much more
elegant

The iteration variable is
completely taken care of by
the for loop
index = 0
while index < len(fruit) :
letter = fruit[index]
print letter
index = index + 1
fruit = 'banana'
for letter in fruit :
print letter
b
a
n
a
n
a
Looping and Counting

This is a simple loop that
loops through each letter in a
string and counts the number
of times the loop encounters
the 'a' character.
word = 'banana'
count = 0
for letter in word :
if letter == 'a' :
count = count + 1
print count
Looking deeper into in

The iteration variable
“iterates” though the
sequence (ordered set)

The block (body) of code is
executed once for each
value in the sequence

The iteration variable
moves through all of the
values in the sequence
for letter in 'banana' :
print letter
Iteration variable
Six-character string
Done?
Yes
print letter
Advance letter
for letter in 'banana' :
print letter
b a n a n a
letter
The iteration variable “iterates” though the string and the block
(body) of code is executed once for each value in the sequence

Xem chi tiết: 06-Strings


Không có nhận xét nào:

Đăng nhận xét