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

Chapter 7 PythonStrngs

Here are some examples of strip() and rstrip(): s = "+++abcd+++" print(s.strip('+')) # "abcd" s = "+++abcd+++" print(s.rstrip('+')) # "+++abcd" The strip() method removes all leading and trailing characters that are in the string c. The rstrip() method only removes trailing characters. So strip() removes characters from both ends, while rstrip() only removes from the right end. This is useful to remove whitespace or other unwanted characters from the edges of a string. 25 Special methods title() Return a titlecased version of the string where words start with

Uploaded by

cjq1222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views31 pages

Chapter 7 PythonStrngs

Here are some examples of strip() and rstrip(): s = "+++abcd+++" print(s.strip('+')) # "abcd" s = "+++abcd+++" print(s.rstrip('+')) # "+++abcd" The strip() method removes all leading and trailing characters that are in the string c. The rstrip() method only removes trailing characters. So strip() removes characters from both ends, while rstrip() only removes from the right end. This is useful to remove whitespace or other unwanted characters from the edges of a string. 25 Special methods title() Return a titlecased version of the string where words start with

Uploaded by

cjq1222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

Chapter 7.

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]

Bubble Sort Algorithm


An animation:
https://upload.wikimedia.org/wikipedia/com
mons/c/c8/Bubble-sort-example-300px.gif
(Note: The end is shortened after each
iteration.)

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]

Pink items: Items that is under consideration for


swapping in that round of j value.
7
Bubble sort (example)
Original list: 6 5 3 1 8 7 2 4
i = 0, j = 0 – 6: 5 3 1 6 7 2 4 8
i = 1, j = 0 – 5: 3 1 5 6 2 4 7 8
i = 2, j = 0 – 4: 1 3 5 2 4 6 7 8
i = 3, j = 0 – 3: 1 3 2 4 5 6 7 8
i = 4, j = 0 – 2: 1 2 3 4 5 6 7 8
i = 5, j = 0 – 1: 1 2 3 4 5 6 7 8
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]
Red items: Items that do not need to be considered
in that round of i value.
8
Outline of “Python String” chapter
In this chapter, you will learn:
 The bracket / index operator
 Positive vs. negative indices
 String methods
 Slicing operation

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

 s[i] for any i >= len ➔ “index out-of-range” error.

10
Negative indices?
 s[e] where e can be any expression whose value is in
[0, len(s)-1]

 In fact, we can have negative index: [-len(s), -1]


 To understand, we duplicated the string, E.g., the string s =
“abcd” with len = len(s) = 4.
a b c d a b c d
-4 = -len -3 -2 -1 0 1 2 3 = len - 1

Again, s[i] for any i < -len ➔ “index out-of-range” error

11
str objects are immutable (i.e., you
cannot change its individual elements)

Recall that a string is in fact a tuple of characters.

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).

The argument s and e can


be omitted.

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.

when the sub string NOT FIND return -1


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

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

join(t) Return a string which is the concatenation of t, but


in a way that passes one string through the other.

Copy from the official definition


(not obvious what it really means)

Easier to understand

19
Special methods
replace(old, new, c) Return a string with first c occurrences of old
replaced by new.

The argument c can be omitted, and then all


occurrences of old will be replaced.

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

You might also like