Unit 3 Powerpoint
Unit 3 Powerpoint
Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring:
Example:
var 1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
Determine if str occurs in string, or in a substring of string if starting index beg and
ending index end are given; returns index if found and -1 otherwise
8 index(str, beg=0, end=len(string))
9 isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise
11 isdigit()
12 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise
13 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace()
Returns true if string contains only whitespace characters and false otherwise
15 istitle()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)
Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()
Replaces all occurrences of old in string with new, or at most max occurrences if max
given
26 rfind(str, beg=0,end=len(string))
28 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width
columns.
29 rstrip()
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given
31 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; Returns true if so, and false otherwise
33 strip([chars])
34 swapcase()
35 title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the
rest are lowercase
36 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the
del string
37 upper()
38 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise
What is Not a “Collection”?
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A List is a Kind of Collection
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
[... 'append', 'count', 'extend',
'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>>
List Methods and Useful Built-
in Functions (cont’d.)
• del statement: removes an element from a specific
index in a list
General format: del list[i]
• min and max functions: built-in functions that
returns the item that has the lowest or highest value
in a sequence
The sequence is passed as an argument
Copying Lists
• To make a copy of a list you must copy each element of the list
Two methods to do this:
• Creating a new empty list and using a for loop to add a copy of each element
from the original list to the new list
• Creating a new empty list and concatenating the old list to the new empty list
Copying Lists (cont’d.)
Processing Lists
• List elements can be used in calculations
• To calculate total of numeric values in a list use loop
with accumulator variable
• To average numeric values in a list:
Calculate total of the values
Divide total of the values by len(list)
• List can be passed as an argument to a function
Lists are Mutable
>>> fruit = 'Banana'
>>> fruit[0] = 'b'
Traceback
TypeError: 'str' object
does not
Strings are “immutable” - we support item assignment
cannot change the contents of a >>> x = fruit.lower()
string - we must make a new >>> print(x)
string to make any change banana
Lists are “mutable” - we can >>> lotto = [2, 14, 26, 41,
change an element of a list 63]
>>> print(lotto)
using the index operator
[2, 14, 26, 41, 63]
>>> lotto[2] = 28
>>> print(lotto)
[2, 14, 28, 41, 63]
total = 0
count = 0
while True : Enter a number: 3
inp = input('Enter a Enter a number: 9
number: ') Enter a number: 5
if inp == 'done' : break Enter a number: done
value = float(inp) Average: 5.66666666667
total = total + value
count = count + 1
numlist = list()
while True :
average = total / count inp = input('Enter a number:
print('Average:', average) ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
average = sum(numlist) /
len(numlist)
print('Average:', average)
Best Friends: Strings and Lists
>>> abc = 'With three words' >>> print(stuff)
>>> stuff = abc.split() ['With', 'three', 'words']
>>> print(stuff) >>> for w in stuff :
['With', 'three', 'words'] ... print(w)
>>> print(len(stuff)) ...
3 With
>>> print(stuff[0]) Three
With Words
>>>
Split breaks a string into parts and produces a list of strings. We think of these
as words. We can access a particular word or loop through all the words.
>>> line = 'A lot of spaces'
>>> etc = line.split()
>>> print(etc)
['A', 'lot', 'of', 'spaces']
>>>
>>> line = 'first;second;third'
>>> thing = line.split()
>>> print(thing)
['first;second;third'] ● When you do not specify a
>>> print(len(thing))
1 delimiter, multiple spaces are
>>> thing = line.split(';') treated like one delimiter
>>> print(thing)
['first', 'second', 'third']
>>> print(len(thing)) ● You can specify what
3 delimiter character to use in
>>>
the splitting
The Double Split Pattern
From [email protected] Sat Jan
5 09:14:16 2008
words = line.split()
email = words[1]
print pieces[1]
[email protected]
The Double Split Pattern
From [email protected] Sat Jan
5 09:14:16 2008
words = line.split()
email = words[1] [email protected]
pieces =
email.split('@')
print pieces[1]
['stephen.marquard', 'uct.ac.za']
The Double Split Pattern
From [email protected] Sat
Jan 5 09:14:16 2008
[email protected]
words = line.split()
email = words[1]
['stephen.marquard', 'uct.ac.za']
pieces =
email.split('@')
print(pieces[1]) 'uct.ac.za
'
List Summary