[go: up one dir, main page]

0% found this document useful (0 votes)
15 views31 pages

05 - Strings and Lists

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views31 pages

05 - Strings and Lists

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Strings & Lists

Lecture 5
Sheet #4
Due Friday Nov. 1st

https://forms.gle/Vaw7khLQ6TSJziFt7
String Data Type
>>> str1 = "Hello"
>>> str2 = 'there'
>>> bob = str1 + str2
>>> print(bob))
• A string is a sequence of characters Hellothere
>>> str3 = '123'
• A string literal uses quotes >>> str3 = str3 + 1
'Hello' or "Hello" Traceback (most recent call
last): File "<stdin>", line 1,
• For strings, + means “concatenate” in <module>
TypeError: cannot concatenate
• When a string contains numbers, it is 'str' and 'int' objects
still a string >>> x = int(str3) + 1
>>> print(x))
124
• We can convert numbers in a string
>>>
into a number using int()
Reading and >>> name = input('Enter:')
Enter:Chuck
Converting >>> print(name)
Chuck
>>> apple = input('Enter:')
• We prefer to read data in using
Enter:100
strings and then parse and
>>> x = apple – 10
convert the data as we need
Traceback (most recent call
last): File "<stdin>", line 1,
• This gives us more control over
in <module>
error situations and/or bad user
TypeError: unsupported operand
input
type(s) for -: 'str' and 'int'
>>> x = int(apple) – 10
• Input numbers must be
>>> print(x)
converted from strings
90
Looking Inside Strings
• We can get at any single character in a b a n a n a
string using an index specified in 0 1 2 3 4 5
square brackets
>>> fruit = 'banana'
• The index value must be an integer
>>>
>>>
letter = fruit[1]
print(letter)
and starts at zero a
>>> x = 3
• The index value can be an expression >>> w = fruit[x - 1]
that is computed >>> print(w)
n
A Character Too Far
• You will get a python error >>> zot = 'abc'
>>> print(zot[5])
if you attempt to index Traceback (most recent call
beyond the end of a string last): File "<stdin>", line
1, in <module>
• So be careful when IndexError: string index out
constructing index values of range
and slices >>>
Strings Have Length

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
len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some
6 input and produces an
output.

'banana' len() 6
(a number)
(a string) function
Looping Through Strings

Using a while statement, fruit = 'banana' 0b


an iteration variable, and index = 0 1a
the len function, we can while index < len(fruit): 2n
letter = fruit[index] 3a
construct a loop to look at
print(index, letter)
each of the letters in a 4n
index = index + 1
string individually 5a
Looping Through Strings

• A definite loop using a b


for statement is much a
fruit = 'banana'
more elegant n
for letter in fruit:
a
• The iteration variable is print(letter)
n
completely taken care of a
by the for loop
Looping Through Strings

• A definite loop using a fruit = 'banana'


for letter in fruit :
b
for statement is much a
print(letter)
more elegant n
a
• The iteration variable is index = 0
n
completely taken care of while index < len(fruit) :
a
by the for loop letter = fruit[index]
print(letter)
index = index + 1
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)
More String Operations
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
>>> print(s[6:20])
• If the second number is
Python
beyond the end of the string,
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

>>> s = 'Monty Python'


If we leave off the first number >>> print(s[:2])
or the last number of the slice, Mo
it is assumed to be the >>> print(s[8:])
beginning or end of the string thon
respectively >>> print(s[:])
Monty Python
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
When the + operator is >>> print(b)
applied to strings, it means HelloThere
“concatenation” >>> c = a + ' ' + 'There'
>>> print(c)
Hello There
>>>
Lists
Python Collections
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
What is Not a “Collection”?
Most of our variables have one value in them - when we put a new
value in the variable, the old value is overwritten

$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A List is a Kind of Collection

• A collection allows us to put many values in a single “variable”

• A collection is nice because we can carry all many values


around in one convenient package.

friends = [ 'Joseph', 'Glenn', 'Sally' ]

carryon = [ 'socks', 'shirt', 'perfume' ]


List Constants
• List constants are surrounded by >>> print([1, 24, 76])
[1, 24, 76]
square brackets and the elements >>> print(['red', 'yellow',
in the list are separated by 'blue'])
commas ['red', 'yellow', 'blue']
>>> print(['red', 24, 98.6])
• A list element can be any Python ['red', 24, 98.6]
>>> print([ 1, [5, 6], 7])
object - even another list [1, [5, 6], 7]
>>> print([])
• A list can be empty []
We Already Use Lists!
5
for i in [5, 4, 3, 2, 1] :
print(i) 4
print('finish!') 3
2
1
finish!
Lists and Definite Loops - Best Pals

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends : Happy New Year: Joseph
print('Happy New Year:', friend)
print('Done!') Happy New Year: Glenn
Happy New Year: Sally
Done!
z = ['Joseph', 'Glenn', 'Sally']
for x in z:
print('Happy New Year:', x)
print('Done!')
Properties of Lists
1. List items are ordered, changeable, and allow duplicate values.

2. List items are indexed, the first item has index [0], the second
item has index [1] etc.

3. Ordered, when we say that lists are ordered, it means that


the items have a defined order, and that order will not
change.

4. If you add new items to a list, the new items will be placed at the end
of the list.
Looking Inside Lists

Just like strings, we can get at any single element in a list using an
index specified in square brackets

>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]


Joseph Glenn Sally >>> print(friends[1])
Glenn
0 1 2 >>>
How Long is a List?

• The len() function takes a list as a >>> greet = 'Hello Bob'


parameter and returns the number >>> print(len(greet))
of elements in the list 9
>>> x = [ 1, 2, 'joe', 99]
• Actually len() tells us the number of >>> print(len(x))
elements of any set or sequence 4
(such as a string...) >>>
Concatenating Lists Using +
>>> a = [1, 2, 3]
We can create a new list >>> b = [4, 5, 6]
by adding two existing >>> c = a + b
>>> print(c)
lists together
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]
Is Something in a List?
>>> some = [1, 9, 21, 10, 16]
• Python provides two operators
>>> 9 in some
that let you check if an item is True
in a list >>> 15 in some
False
• These are logical operators >>> 20 not in some
that return True or False True
>>>
• They do not modify the list
Built-in Functions and Lists
>>> nums = [3, 41, 12, 9, 74, 15]
• There are a number of >>> print(len(nums))
functions built into Python 6
that take lists as >>> print(max(nums))
parameters 74
>>> print(min(nums))
• Remember the loops we 3
>>> print(sum(nums))
built? These are much 154
simpler. >>> print(sum(nums)/len(nums))
25.6
append Function
To add an item to the end of the list, use the append() method:
Example:
• Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

• Output:

['apple', 'banana', 'cherry', 'orange']


Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

You might also like