05 - Strings and Lists
05 - Strings and 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
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A List is a Kind of Collection
2. List items are indexed, the first item has index [0], the second
item has index [1] etc.
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
• Output: