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 number)
(a string) function
def len(inp):
blah
'banana' blah 6
for x in y: (a number)
(a string) 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
>>> c = a + ' ' + 'There'
applied to strings, it
means "concatenation" >>> print c
Hello There
>>>
Using in as an Operator
>>> fruit = 'banana’
• The in keyword can also be >>> 'n' in fruit
used to check to see if one True
string is "in" another string >>> 'm' in fruit
False
• The in expression is a >>> 'nan' in fruit
True
logical expression and >>> if 'a' in fruit :
returns True or False and ... print 'Found it!’
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 to b a n a n a
search for a substring within 0 1 2 3 4 5
another string
>>> fruit = 'banana'
• find() finds the first >>> pos = fruit.find('na')
occurance of the substring >>> print pos
2
• If the substring is not found,
>>> aa = fruit.find('z')
find() returns -1
>>> print aa
• Remember that string -1
position starts at zero
Making everything UPPER CASE