You are on page 1of 25

Strings and Lists

Dr. Mohammed Eunus Ali


(eunus@cse.buet.ac.bd)

Department of Computer Science and Engineering


Bangladesh University of Engineering and Technology (BUET)
Dhaka-1000, Bangladesh
Strings
• String: A sequence of text characters in a program
– Strings start and end with quotation mark " or apostrophe ' characters.
– Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
• A string may not span across multiple lines or contain a " character:
"This is not
a legal String."
"This is not a "legal" String either."
• A string can represent characters by preceding them with a
backslash
– \t tab character
– \n new line character
– \" quotation mark character
– \\ backslash character

– Example: "Hello\tthere\nHow are you?"

2
Strings
• String: A sequence of text characters in a program
– Strings start and end with quotation mark " or apostrophe ' characters.
– Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
• A string may not span across multiple lines or contain a " character:
"This is not
a legal String."
"This is not a "legal" String either."
• A string can represent characters by preceding them with a
backslash
– \t tab character
– \n new line character
– \" quotation mark character
– \\ backslash character

– Example: "Hello\tthere\nHow are you?"

3
Indexes

• Characters in a string are numbered with indexes


starting at 0:
– Example:
name = “Hello Bob"
index 0 1 2 3 4 5 6 7 8
character H e l l o B o b

• Accessing an individual character of a string:


variableName [ index ]

– Example:
print name, "starts with", name[0]

Output:
Hello Bob starts with H 4
Indexes

name = “Hello Bob"


index 0 1 2 3 4 5 6 7 8
character H e l l o B o b

In a string of n characters, the last character is at position n-1 since we


start counting with 0

We can index from the right side using negative indexes


>>> name[-1]
'b'
>>> name[-3]
'B'

5
Slicing
• Indexing returns a string containing a single character from a larger
string
• We can also access a contiguous sequence of characters, called a
substring, through a process called slicing
• Slicing:
– <string>[<start>:<end>]
– start and end should both be integer
• The slice contains the substring beginning at position start and runs
up to but doesn’t include the position end. Example:
>>> name[0:3]
'Hel'
>>> name[5:9]
' Bob'
>>> name[:5]
'Hello'
>>> name5:]
' Bob'
>>> name[:]
'Hello Bob'

6
String Operations
• Can we put two strings together into a longer string?
• Concatenation “glues” two strings together (+)
• Repetition builds up a string by multiple concatenations
of a string with itself (*)
• Example:
>>> "Spam" + "And" + "Eggs"
'SpamAndEggs'
>>> 3 * "spam"
'spamspamspam'

7
String Operations

Operator Meaning
+ Concatenation
* Repetition
<string>[] Indexing
<string>[:] Slicing
len(<string>) Length
For <var> in <string> Iteration through characters

8
Strings

• Strings are immutable:


– By immutable, we mean that they cannot be changed:
• can't be appended to
• can't change elements, i.e. re-assign their values
• can't delete elements
• String Input:
– raw_input : Reads a string of text from user input
– Example:
name = raw_input("What's your name? ")
print name, "... what a silly name!"

Output:
What's your name? Tiger Woods
Tiger Woods... what a silly name!
9
Text Processing
• Text processing: Examining, editing, formatting text.
– often uses loops that examine the characters of a string one by one

• A for loop can examine each character in a string in


sequence.
– Example:
for c in "booyah":
print c
Output:
b
o
o
y
a
h

10
Strings and Numbers

• ord(text) - converts a string into a number.


– Example: ord("a") is 97, ord("b") is 98, ...

– Characters map to numbers using standardized mappings such


as ASCII and Unicode.

• chr(number) - converts a number into a string.


– Example: chr(99) is "c"

11
String Functions
• lower() is a function that converts a string into lowercase. Example:
message = "Hello"
print message
message.lower() #no effect print message
message = message.lower()
print message

Output:
Hello
Hello
hello

12
String Functions

• Functions that return a new string


– str.capitalize() / str.lower(). Returns a copy of str with all letters
converted to uppercase / lowercase.
– str.strip(). Returns a copy of strwith all whitespace
(spaces/tabs/newlines) from thebeginning and end of the string
removed.Example: " test ".strip() == "test".
– str.replace(old,new). Returns a copy of strwith all instances of
oldwithin the stringreplaced with new.Example: "hallo
all!".replace("al", "el") == "hello ell!".

13
String Functions

• Functions which return information about a string


– str.count(substring).
– Returns the number of times substringappears within str.
– str.find(substring) / str.rfind(substring).
– Returns the position of the first instance of substringwithin str.
rfind returns the position of the last instance of substring.
– s.startswith(substring) / str.endswith(substring).
• Returns True if the string starts with / ends with substring.
• Example: "Hello".startswith(“he”) == False, but
“Hello”.endswith(“lo”) == True

14
String Functions

• Functions which transform the string into other


types
– str.split(separator). Returns a list of words in str, using separator
as the delimiter string.
• Example: "hello world, Mihir here".split("
")returns["hello","world,","Mihir","here"].
• Example: "mississippi".split("s")returns ["mi", "", "i", "", "ippi"].
– separator.join(seq). This one is tricky. It takes a list of strings seq
and combines them into a string. Each element in seqis
separated by separatorin the returned string.
• Example: " ".join(["hello","world"]) == "hello world"

15
Lists

• A list stores a sequence of elements [x1,x2,x3,...]. Note that


order matters: [x1,x2] != [x2,x1]
• You can store different types of variables in the same list:
– [1,3,"test",True]
• You can create a list using square brackets:
– [1,2,5,1,3,"test"]
• To read an element from list some_list, use some_list[index].
– The index of an element is just its position, but note that the first
element is considered to have a position of 0!
– The built-in function len(x) will find the length of any list passed in as
a parameter

16
Lists and Arrays
• A list or array is a sequence of items where the entire sequence is
referred to by a single name (i.e. s) and individual items can be
selected by indexing (i.e. s[i]).

• In other programming languages, arrays are generally a fixed size,


meaning that when you create the array, you have to specify how
many items it can hold.

• Arrays in other programming languages are generally also


homogeneous, meaning they can hold only one data type.

• Python List:
– Python lists are dynamic. They can grow and shrink on demand.
– Python lists are also heterogeneous, a single list can hold arbitrary data types.
– Python lists are mutable sequences of arbitrary objects.

17
Basic List Operations

Operator Meaning
<seq> + <seq> Concatenation
<seq> * <int-expr> Repetition
<seq>[] Indexing
len(<seq>) Length
<seq>[:] Slicing
for <var> in <seq>: Iteration
<expr> in <seq> Membership (Boolean)

18
Example

>>> fruit = ["banana", "apple", "quince"]


>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
['pear', 'apple', 'orange']

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']


>>> list[1:3] = ['x', 'y']
>>> print list
['a', 'x', 'y', 'd', 'e', 'f']

19
Example
Example 1:
some_list = [3,6,2,5]
i=1
while i < 3:
print some_list[i], ";"
i=i+1
print some_list[3]
Example 2:
NAMES = ["Alice", "Bob", "Cathy", "Doug"]
for i in range(len(NAMES )):
print "Hello", NAMES [i]
i=i+1
print "We're out of names!"
print "The last name we saw was", NAMES[i]

**ANY ERROR IN EXAMPLE 2 ??

20
List Member Functions

Method Meaning

<list>.append(x) Add element x to end of list.

<list>.sort() Sort (order) the list. A comparison function may be passed as a


parameter.
<list>.reverse() Reverse the list.

<list>.index(x) Returns index of first occurrence of x.

<list>.insert(i, x) Insert x into list at index i.

<list>.count(x) Returns the number of occurrences of x in list.

<list>.remove(x) Deletes the first occurrence of x in list.

<list>.pop(i) Deletes the ith element of the list and returns its value.

Syntax of calling: object_name.function(parameters) 21


Example
>>> lst = [3, 1, 4, 1, 5, 9]
>>> lst.append(2)
>>> lst
[3, 1, 4, 1, 5, 9, 2]
>>> lst.sort()
>>> lst
[1, 1, 2, 3, 4, 5, 9]
>>> lst.reverse()
>>> lst
[9, 5, 4, 3, 2, 1, 1]
>>> lst.index(4)
2
>>> lst.insert(4, "Hello")
>>> lst
[9, 5, 4, 3, 'Hello', 2, 1, 1]
>>> lst.count(1)s
2
>>> lst.remove(1)
>>> lst
[9, 5, 4, 3, 'Hello', 2, 1]
>>> lst.pop(3)
3
>>> lst
[9, 5, 4, 'Hello', 2, 1]

22
Example

• >>> myList=[34, 26, 0, 10]


>>> del myList[1]
>>> myList
[34, 0, 10]
>>> del myList[1:3]
>>> myList
[34]

• del isn’t a list method, but a built-in operation that can be


used on list items.

23
Call By Reference

example_list = []
def append_one(my_list):
#"This is a function that adds something to the end of a
list"
Heap
my_list.append(1)
Name,type value
print id(my_list) [1]
example_list, list
print id(example_list) my_list, list (local)

append_one(example_list)
print example_list

24
Nested Lists

• A nested list is a list that appears as an element in


another list. In this list, the three-eth element is a
nested list:
>>> list = ["hello", 2.0, 5, [10, 20]]
>>> print list[3]
[10,20]

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


>>> matrix[1]
[4, 5, 6]
>>> matrix[1][1]
5

25

You might also like