Strings: Python For Informatics: Exploring Information
Strings: Python For Informatics: Exploring Information
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
A function is some
>>> fruit = 'banana'
stored code that we
>>> x = len(fruit)
use. A function takes
>>> print x
some input and
6
produces an output.
'banana' len() 6
(a string) (a number)
function
def len(inp):
blah
'banana' blah 6
for x in y: (a number)
(a string) blah
blah
Looping Through Strings
print letter
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
• The in keyword can also >>> fruit = 'banana’
>>> 'n' in fruit
be used to check to see if
True
one string is "in" another >>> 'm' in fruit
string False
>>> 'nan' in fruit
• The in expression is a True
logical expression and >>> if 'a' in fruit :
... print 'Found it!’
returns True or False and
...
can be used in an if Found it!
statement >>>
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 search for a substring b a n a n a
within another string 0 1 2 3 4 5
• find() finds the first >>> fruit = 'banana'
occurance of the >>> pos = fruit.find('na')
substring >>> print pos