Professional Documents
Culture Documents
04 String PL
04 String PL
b a n a n a
0 1 2 3 4 5
• There is a built-in function len that
gives us the length of a string >>> fruit = 'banana'
>>> print len(fruit)
6
Len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print x function takes some input
6 and produces an output.
'banana' len() 6
(a string) function (a number)
def len(inp):
blah
'banana' blah 6
(a string) for x in y: (a number)
blah
blah
Looping Through Strings
fruit = 'banana' 0b
• Using a while statement and index = 0 1a
an iteration variable, and the while index < len(fruit) : 2n
len function, we can construct letter = fruit[index] 3a
a loop to look at each of the print index, letter 4n
letters in a string individually index = index + 1 5a
Looping Through Strings
print letter
The iteration variable “iterates” though the string and the block
(body) of code is executed once for each value in the sequence
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
Slicing Strings
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
>>> print b
• When the + operator is HelloThere
applied to strings, it >>> c = a + ' ' + 'There'
means "concatenation" >>> print c
Hello There
>>>
Using in as an Operator
>>> fruit = 'banana’
• The in keyword can also be >>> 'n' in fruit
True
used to check to see if one >>> 'm' in fruit
string is "in" another string False
>>> 'nan' in fruit
• The in expression is a logical True
expression and returns True >>> if 'a' in fruit :
... print 'Found it!’
or False and can be used in
...
an if statement Found it!
>>>
String Comparison
if word == 'banana':
print 'All right, bananas.'
http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/string-methods.html
String Library
http://docs.python.org/lib/string-methods.html
Searching a
String
• We use the find() function b a n a n a
to search for a substring
within another string
0 1 2 3 4 5