Chapter 7 PythonStrngs
Chapter 7 PythonStrngs
Python Strings
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
An Interesting Quiz Question
What is the output of the following program?
Answer:
[3, 4, 5, 6, 7, 8, 9]
2
Bubble sort
This is actually another famous sorting algorithm
called bubble sort.
Bubble sort examines the list from start to finish,
comparing elements as it goes. Any time it finds a
larger element before a smaller element, it swaps
the two.
In this way, the larger elements are passed towards
the end. The largest element of the array therefore
"bubbles" to the end of the array.
Then it repeats the process for the unsorted portion
of the array until the whole array is sorted.
3
Bubble sort
Bubble sort works on the same general principle as
shaking a soft drink bottle.
Right after shaking, the contents are a mixture of
bubbles and soft drink, distributed randomly.
Because bubbles are lighter than the soft drink, they
rise to the surface, displacing the soft drink
downwards.
This is how bubble sort got its name, because the
smaller elements "float" to the top, while the larger
elements "sink" to the bottom.
4
Bubble sort (algorithm)
Define the entire list as the unsorted portion of the
list.
While the unsorted portion of the list has more than
one element:
For every element in the unsorted portion, swap
with the next neighbor if it is larger than the next
neighbor.
Reduce the size of the unsorted portion of the
list by 1.
5
Bubble sort (algorithm)
Python code:
for i in range(size):
for j in range(0, size – 1 – i):
if x[j] > x[j + 1]:
x[j], x[j + 1] = x[j + 1], x[j]
6
Bubble sort (example)
Original list: 6 5 3 1 8 7 2 4
i = 0:
j = 0: 5 6 3 1 8 7 2 4 After each round of i value, the
greatest element goes to the bottom!
j = 1: 5 3 6 1 8 7 2 4
j = 2: 5 3 1 6 8 7 2 4
j = 3: 5 3 1 6 8 7 2 4
Python code:
j = 4: 5 3 1 6 7 8 2 4 for i in range(size):
for j in range(0, size – 1 – i):
j = 5: 5 3 1 6 7 2 8 4 if x[j] > x[j + 1]:
j = 6: 5 3 1 6 7 2 4 8 x[j], x[j + 1] = x[j + 1], x[j]
9
The bracket operator []
Given a string, we can use the square bracket [] operator to
access its elements individually by their “indices”.
Example:
s = “abcdef”
a b c d e f
s[0] s[1] s[2] s[3] s[4] s[5]
In general, given a string s of length len, its first element has index 0,
the second element index 1, ..., the last element index len-1.
a b ...
0 1 ... len - 1
10
Negative indices?
s[e] where e can be any expression whose value is in
[0, len(s)-1]
11
str objects are immutable (i.e., you
cannot change its individual elements)
12
Build-in methods for strings
Unlike functions like len() that takes a string as an argument
and returns the length of the string, methods are directly
associated with the string (thus, we don’t need to pass the
string as argument).
Example: the method isupper() returns true if the string
contains only upper-case letter. Apply the method
isupper() to s to test if
the string s has ONLY
upper case letters.
13
Boolean methods
isupper() return True if ALL the alphabet characters in the string are in
uppercase, and return False otherwise
islower() return True if ALL the alphabet characters in the string are in
, and return False otherwise
isnumeric() return True if the string has ONLY digits 0, 1, 2, ..., 9
isalpha() return True if the string has ONLY letters a, ..., z, A,...,Z
isspace() return True if there are ONLY whitespace characters in the
string, whitespace characters include tabs, spaces, newline, etc.
14
Methods returning statistical information
count(t, s, e) Return the number of non-
overlapping occurrence of
substring t in the range
[s,e).
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
o o o a b c o o o d e f o o o g h i
15
Methods returning statistical information
find(t, s, e) Return the lowest index in the string where t occurs
t = sub string with the range [s, e).
Again, s and e can be omitted.
t h e m a n t h e b o y a n d t h e d o 16g
Write a program that reads in a string s and then prints the
location(s) of the substring “the” in s.
17
Special methods
Easier to understand
19
Special methods
replace(old, new, c) Return a string with first c occurrences of old
replaced by new.
Note that a.replace() returns a new string. a is not modified. You can write
b = a.replace() to obtain the new string. 20
Another example
Write a Python function replace_nth(a, n) that returns a string
that is constructed by replacing the nth occurrence of “the” in a
by the string “an”. If a does not have any occurrence of “the”,
the function returns the empty string “”.
Some examples
21
Another example
Solution:
22
Special methods
split(t) Return a list of substrings separated by t.
23
Read a line of digit-strings separated by space,
and print a list of their corresponding values.
24
Special methods
strip(c) Return a string in which all the leading and trailing c
removed.
rstrip(c) Return a string in which all the trailing c removed.
26
The +, *, and the in operator
27
Strings slicing using []
s = "Hello world!"
s[1:4] ➔ the substring of s starting from s[1], and ending at s[3], i.e., s[1:4] =
"ell"
s[a:b] ➔ the substring starts at index a (inclusive), with increment step 1
(default), and ends at index b (exclusive). i.e., the substring
s[a]s[a+1]...s[b-1].
s[:b]: starts at the index 0, and ends at s[b-1]
s[a:]: starts at index a, and ends at the last character, i.e., at the index len(s)-1.
s[a:b:c] ➔ the substring starts at index a (inclusive), with increment step
c, and ends at the largest possible index smaller than b (exclusive). i.e.,
the substring s[a]s[a+c]s[a+2c]...s[a+kc] where k is an integer and a+kc <=
b-1.
s[:b:c]: starts at the index 0, and ends at kc where k is an integer and kc <= b-1
s[a::c]: starts at index a, and ends at kc where k is an integer and a+kc <= len(s)-1
28
Strings slicing using slice()
s = "Hello world!“
x = slice(1,4,1)
s[x] ➔ the substring of s starting from s[1], and ending at s[3], i.e., s[x] =
"ell"
s[slice(a,b,1)] ➔ the substring starts at index a (inclusive), with
increment step 1 (default), and ends at index b (exclusive). i.e.,
the substring s[a]s[a+1]...s[b-1].
s[slice(a,b,c)] ➔ the substring starts at index a (inclusive), with
increment step c, and ends at the largest possible index smaller
than b (exclusive). i.e., the substring s[a]s[a+c]s[a+2c]...s[a+kc]
where k is an integer and a+kc <= b-1.
All 3 arguments must be provided to the slice() function.
29
Examples
30
A palindrome is a type of word play in which a word or phrase spelled
forward is the same word or phrase spelled backward. E.g., racecar, refer.
Write a function is_pal (s), which returns True if s is a palindrome, and False
otherwise. The function should contain one statement only and there
should be no recursive function call.
31
Slicing can also be applied to lists and tuples
33
Chapter 7.
END
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong