Python 06 Strings
Python 06 Strings
Chapter 6
String Data Type
• A string is a sequence of characters
b a n a n a
The built-in function len gives 0 1 2 3 4 5
us the length of a string
>>> fruit = 'banana'
>>> print(len(fruit))
6
Looping Through Strings
• The iteration variable is
fruit = 'banana'
index = 0
completely taken care of while index < len(fruit) : b
by the for loop letter = fruit[index] a
print(letter)
index = index + 1
n
a
n
• A definite loop using a fruit = 'banana' a
for statement is much for letter in fruit :
more elegant print(letter)
Looping and Counting
word = 'banana'
This is a simple loop that count = 0
loops through each letter in a for letter in word :
string and counts the number if letter == 'a' :
of times the loop encounters count = count + 1
the 'a' character print(count)
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string
using a colon operator >>> s = 'Monty Python'
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
• If the second number is >>> print(s[6:20])
beyond the end of the string, Python
it stops at the end
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
https://docs.python.org/3/library/stdtypes.html#string-
methods
Searching a String
b a n a n a
• We use the find() function to search
for a substring within another string
0 1 2 3 4 5
•
>>> nstr = greet.replace('o','X')
It replaces all >>> print(nstr)
occurrences of the HellX BXb
search string with the >>>
replacement string
Stripping Whitespace
• Sometimes we want to take
a string and remove
whitespace at the beginning >>> greet = ' Hello Bob '
and/or end >>> greet.lstrip()
'Hello Bob '
Idea: find the @ symbol in the string, and the first whitespace
character after the at-sign. Then use string slicing to extract
the desired portion of the string
Parsing and Extracting
>>> data = 'From [email protected] Sat Jan 5
09:14:16 2008'
>>> startPos = data.find('@')
>>> print(startPos)
21
>>> endPos = data.find(' ', startPos)
>>> print(endPos)
31
>>> host = data[startPos +1 : endPos]
>>> print(host)
uct.ac.za
Format Operator
• The format operator, % allows us to construct strings, replacing
parts of the strings with the data stored in variables.
• We use “%d” to format an integer, “%g” to format a floating point
number, and “%s” to format a string
>>> Items = 32
>>> 'We have %d items' % Items
'We have 32 items‘