Strings
Chapter 6
Python for Informatics: Exploring Information
www.pythonlearn.com
Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.
Copyright 2010- Charles Severance
String Data Type
>>> str1 = "Hello”
>>> str2 = 'there'
>>> bob = str1 + str2
>>> print bob
Hellothere
>>> str3 = '123'
>>> str3 = str3 + 1
Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects
>>> x = int(str3) + 1
>>> print x
124
>>>
Reading and Converting
>>> name = raw_input('Enter:')
Enter:Chuck
>>> print name
Chuck
>>> apple = raw_input('Enter:')
Enter:100
>>> x = apple – 10
Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> x = int(apple) – 10
>>> print x
90
Looking Inside Strings
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print letter
a
>>> n = 3
>>> w = fruit[n - 1]
>>> print w
n
0
b
1
a
2
n
3
a
4
n
5
a
A Character Too Far
>>> 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
>>> 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
fruit = 'banana'
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
b
a
n
a
n
a
fruit = 'banana'
for letter in fruit :
print letter
Looping Through Strings
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
word = 'banana'
count = 0
for letter in word :
if letter == 'a' :
count = count + 1
print count
Looking deeper into in
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
The iteration variable “iterates” though the string and the block (body) of code is executed once for each value in the sequence
Slicing Strings
>>> s = 'Monty Python'
>>> print s[0:4]
Mont
>>> print s[6:7]
P
>>> print s[6:20]
Python
0
M
1
o
2
n
3
t
4
y
5
6
P
7
y
8
t
9
h
10
o
11
n
Slicing Strings
>>> s = 'Monty Python'
>>> print s[:2]
Mo
>>> print s[8:]
Thon
>>> print s[:]
Monty Python
0
M
1
o
2
n
3
t
4
y
5
6
P
7
y
8
t
9
h
10
o
11
n
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
>>> print b
HelloThere
>>> c = a + ' ' + 'There'
>>> print c
Hello There
>>>
Using in as an Operator
>>> fruit = 'banana’
>>> 'n' in fruit
True
>>> 'm' in fruit
False
>>> 'nan' in fruit
True
>>> if 'a' in fruit :
... print 'Found it!’
...
Found it!
>>>
String Comparison
if word == 'banana':
print 'All right, bananas.'
if word < 'banana':
print 'Your word,' + word + ', comes before banana.’
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.’
else:
print 'All right, bananas.'
String Library
>>> greet = 'Hello Bob'>>> zap = greet.lower()>>> print zaphello bob
>>> print greet
Hello Bob>>> print 'Hi There'.lower()
hi there
>>>
http://docs.python.org/lib/string-methods.html
>>> stuff = 'Hello world’
>>> type(stuff)<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
http://docs.python.org/lib/string-methods.html
String Library
str.capitalize()
str.center(width[, fillchar])
str.endswith(suffix[, start[, end]])
str.find(sub[, start[, end]])
str.lstrip([chars])
str.replace(old, new[, count])
str.lower()
str.rstrip([chars])
str.strip([chars])
str.upper()
http://docs.python.org/lib/string-methods.html
Searching a String
>>> fruit = 'banana'
>>> pos = fruit.find('na')
>>> print pos
2
>>> aa = fruit.find('z')
>>> print aa
-1
0
b
1
a
2
n
3
a
4
n
5
a
Making everything UPPER CASE
>>> greet = 'Hello Bob'
>>> nnn = greet.upper()
>>> print nnn
HELLO BOB
>>> www = greet.lower()
>>> print www
hello bob
>>>
Search and Replace
>>> greet = 'Hello Bob'
>>> nstr = greet.replace('Bob','Jane')
>>> print nstr
Hello Jane
>>> nstr = greet.replace('o','X')
>>> print nstrHellX BXb
>>>
Stripping Whitespace
>>> greet = ' Hello Bob '
>>> greet.lstrip()
'Hello Bob '
>>> greet.rstrip()
' Hello Bob'
>>> greet.strip()
'Hello Bob'
>>>
>>> line = 'Please have a nice day’
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Prefixes
>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008’
>>> atpos = data.find('@')
>>> print atpos
21
>>> sppos = data.find(' ',atpos)
>>> print sppos
31
>>> host = data[atpos+1 : sppos]
>>> print host
uct.ac.za
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
21
31
Parsing and
Extracting
Summary