Py4Inf 06 Strings
Py4Inf 06 Strings
Chapter 6
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
0b
• Using a while statement and index = 0
while index < len(fruit) :
1a
an iteration variable, and the 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
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
>>> c = a + ' ' + 'There'
applied to strings, it
means "concatenation" >>> print c
Hello There
>>>
Using in as an Operator
>>> fruit = 'banana'
>>> 'n' in fruit
• The in keyword can also be 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 :
or False and can be used in ... print 'Found it!'
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
str.capitalize() str.replace(old, new[, count])
str.lstrip([chars]) str.upper()
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 0 1 2 3 4 5
within another string