L-4

Python Strings

ENGG1330
Computer Programming I

HKU School of Computing and Data Science

L-3: What Your Survey Told Us

Traced the loop correctly
90%
Not yet confident or need help
65%
Loops felt most difficult
33%
2

A String Can Describe a Webpage

What It RepresentsText Stored in a StringWhat We Can Do
Webpage (HTML)<h1>Hello, Ada!</h1>Build a page heading
Python programprint('Hello, Ada!')Generate source code
App response (JSON){"temperature": 24.5}Read weather data
DNA sequenceACGTGCAATGFind a pattern

Strings carry structure, instructions, and data

3

A String Is a Sequence

text = 'Python'print(text)print(len(text))print(text[0])print(len(''))
Download: lec_04_string_sequence.py
4

Strings Can Contain Unicode Text

text = 'café'print(text)print(len(text))print(text[-1])print('🍌')
Download: lec_04_unicode_text.py
5

Either Quote Style Can Delimit a String

print("Hello 'Python'")print('Hello "Python"')print('Hello \'Python\'')
Download: lec_04_quotation_marks.py
6

A Matching Quote Ends the String

7

Escape Sequences Represent Special Characters

EscapeMeaning
\nNew line
\tNext tab stop
\'Single quote
\"Double quote
\\Backslash
text = 'Hello\nWorld'print(text)print(repr(text))
Download: lec_04_escape_characters.py
repr(text) returns a string showing quotes and escape sequences
8

Newlines and Tabs Control the Layout

text = '*\t*\n**\t**\n***\t***'print(text)
Download: lec_04_newlines_tabs.py
9

Triple Quotes Retain Line Breaks

text = """Thisisamultiline string"""print(text)print(repr(text))
Download: lec_04_multiline_strings.py
10

Raw Strings Preserve Backslashes

print('C:\\some\name')print(r'C:\some\name')
Download: lec_04_raw_strings.py
11

String Operations

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
12

Concatenation Creates a New String

description = 'immutable'message = 'Strings are ' + description + ' at all times'print(message)
Download: lec_04_concatenation.py
13

Adjacent Literals Join Automatically

message = ('Vigorous writing is concise. '           'Every word should contribute.')print(message)first = 'Py'second = 'thon'print(first + second)
Download: lec_04_adjacent_literals.py
14

An Integer Repeats a String

print('Ha' * 3)print(3 * 'un' + 'ium')print(repr('Ha' * 0))print(repr('Ha' * -2))
Download: lec_04_repetition.py
15

An Index Selects One Character

text = "You miss all shots you don't take"for index in [0, -1, -10, 10]:    print(index, repr(text[index]))
Download: lec_04_indexing.py

text[0]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1

text[-1]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1

text[-10]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1

text[10]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1
16

A Loop Can Visit Characters Directly

text = 'dirk'for index in range(len(text)):    if text[index] == 'i' or text[index] == 'u':        print('Found i or u')        breakfor char in text:    if char == 'i' or char == 'u':        print('Found i or u')        break
Download: lec_04_character_loops.py
17

Robot Cheerleader

word = input('Word: ')times = int(input('Enthusiasm (1-10): '))for char in word:    print('Give me a ' + char + '! ' + char)print('What does that spell?')print((word + '!!! ') * times)
Download: lec_04_robot_cheerleader.py
18

Membership Tests for a Substring

print('a' in 'program')print('at' not in 'battle')print('battle' in 'at')
Download: lec_04_membership.py
19

Membership Improves the Cheerleader

word = input('Uppercase word: ')an_letters = 'AEFHILMNORSX'for char in word:    article = 'a'    if char in an_letters:        article = 'an'    print('Give me ' + article + ' ' + char + '! ' + char)print(word, '!!!')
Download: lec_04_robot_articles.py
20

A Slice Stops Before Its Stop Index

text = "You miss all shots you don't take"print(text[13:17])print(text[4:])print(text[:3])
Download: lec_04_slicing.py

text[13:17]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[4:]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[:3]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
21

Negative Indices Count from the End

text = "You miss all shots you don't take"print(text[-4:])print(text[-10:-5])print(text[-10:])
Download: lec_04_negative_slices.py

text[-4:]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1

text[-10:-5]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1

text[-10:]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
-33-32-31-30-29-28-27-26-25-24-23-22-21-20-19-18-17-16-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1
22

A Step Selects Spaced Characters

text = "You miss all shots you don't take"print(text[1:10:1], text[1:10:2], sep=" | ")print(text[1:10:3])print(text[::3])
Download: lec_04_slice_step.py

text[1:10:1]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[1:10:2]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[1:10:3]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[::3]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
23

A Negative Step Moves Backwards

text = "You miss all shots you don't take"print(text[10:1:-1])print(text[10:1:-2])print(text[::-1])
Download: lec_04_reverse_slices.py

text[10:1:-1]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[10:1:-2]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take

text[::-1]

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
24

Slicing Can Reach Beyond the String

text = 'Python'print(text[:100])print(repr(text[100:]))
Download: lec_04_slice_boundaries.py
25

An Index Must Select an Existing Character

text = 'Python'print(text[100])
Download: lec_04_index_boundary_error.py
26

Strings Compare at the First Difference

print('Apple' == 'Apple')print('Apple' != 'Apple')print('Apple' < 'Apple')print('Apple' <= 'Apple')print('cat' < 'car')print('HKU' < 'CUHK')
Download: lec_04_string_comparison.py
27

String Functions and Methods

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
28

Finding the Operation You Need

QuestionReference
A function such as len or ordBuilt-in Functions
An operation such as upper or splitString Methods
29

A Function Returns a Result to Its Caller

def is_palindrome(text):    return text == text[::-1]print(is_palindrome('test'))print(is_palindrome('madam'))print(is_palindrome('Anna'))
Download: lec_04_palindrome.py
Argument: 'madam'Parameter: textReturn value: True
'Anna'Case-sensitive comparison'annA'
30

Returning a Value and Printing Output

def double(number):    return number * 2def show_double(number):    print(number * 2)print(double(5) + 1)result = show_double(5)print(result)
Download: lec_04_return_versus_print.py
31

A Loop Can Check the Same Palindrome

def is_palindrome(text):    index = 0    for char in reversed(text):        if char != text[index]:            return False        index += 1    return Trueprint(is_palindrome('madam'))print(is_palindrome('Anna'))
Download: lec_04_palindrome_loop.py
32

ord Gives a Character’s Code Point

print(ord('a'), ord('A'))print(ord('1'), ord('2'))print(ord('é'))
Download: lec_04_code_points.py
33

chr Converts a Code Point to Text

print(chr(65))print(chr(ord('é')))for number in range(65, 91):    print(chr(number), end=' ')print()
Download: lec_04_characters_from_codes.py
34

String Comparison Is Case Sensitive

print('HKU' == "HKU")print('HKU' == 'HkU')print(ord('K'), ord('k'))print('HKU' < 'HkU')
Download: lec_04_case_comparison.py
35

Useful String Methods

MethodPurpose
capitalize()Capitalise the first character; lowercase the rest
upper(), lower()Change case
split()Split into a list of strings
find()Find a substring, or return −1
count()Count non-overlapping occurrences
isalnum(), isalpha()Test alphanumeric or alphabetic text
isdecimal()Test for decimal digit characters
strip()Remove leading and trailing whitespace
replace()Return text with replacements
36

Case Methods Return a New String

name = 'DiRk'print(name.capitalize())print(name.upper())print(name.lower())print(name)
Download: lec_04_case_methods.py
37

Searching and Splitting Text

text = 'red blue red'print(text.split())print(text.find('blue'))print(text.find('green'))print(text.count('red'))
Download: lec_04_search_and_split.py
38

Check the Start or End of a String

filename = 'report.csv'print(filename.endswith('.csv'))address = 'https://hku.hk'print(address.startswith('https://'))print('report.csv.bak'.endswith('.csv'))
Download: lec_04_prefix_suffix.py
39

Character Tests Return Booleans

print('HKU1330'.isalnum())print('HKU'.isalpha())print('1330'.isdecimal())print('-3'.isdecimal())print('3.5'.isdecimal())print(''.isalpha())
Download: lec_04_character_tests.py
40

Removing Whitespace and Replacing Text

text = '  Hello HKU  'print(repr(text.strip()))print(repr(text.replace('HKU', 'Python')))print(repr(text))
Download: lec_04_strip_replace.py
41

Immutability and F-Strings

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
42

A String’s Characters Cannot Be Reassigned

text = 'change me'text[0] = 'a'
Download: lec_04_immutable_assignment.py
43

A String’s Characters Cannot Be Deleted

text = 'delete me'del text[1]
Download: lec_04_immutable_deletion.py
44

Slicing Can Omit a Character

text = "You miss all shots you don't take"changed = text[:29] + text[30:]print(changed)print(text)
Download: lec_04_remove_character.py

Index 29: t

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
45

Slicing Can Replace a Character

text = "You miss all shots you don't take"changed = text[:29] + 'f' + text[30:]print(changed)print(text)
Download: lec_04_replace_character.py

Index 29: t

01234567891011121314151617181920212223242526272829303132
You miss all shots you don't take
46

A List Can Be Edited and Joined

text = 'Test'letters = list(text)letters[1] = 'E'changed = ''.join(letters)print(letters)print(changed)print(text)
Download: lec_04_list_join.py
47

Split and Join Clean Up Extra Spaces

name = '  Ada   Lovelace  'words = name.split()cleaned = ' '.join(words)print(words)print(repr(cleaned))
Download: lec_04_clean_whitespace.py
48

F-Strings Insert Expression Values

name = 'Dirk'student = {'name': 'Dirk', 'age': 21}print(f'My name is {name}')print(f"{student['name']} is {student['age']} years old")
Download: lec_04_f_strings.py
49

Alignment Uses a Minimum Field Width

name = 'Dirk'print(f'|{name:<20}|')print(f'|{name:^20}|')print(f'|{name:>20}|')print(f'|{name:0>20}|')
Download: lec_04_alignment.py
50

Zero Padding Keeps Numbers Aligned

for number in [5, 9, 10, 15]:    print(f'{number:03}')
Download: lec_04_zero_padding.py
51

Precision Controls Decimal Places

pi = 3.14159265print(f'Pi is {pi:.4f}')print(pi)
Download: lec_04_precision.py
52

Encryption and Sorting

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
53

Encryption Uses a Key

Plain text and a key are inputs to encryption, producing cipher text
Plain text and a key produce cipher text
54

A Caesar Cipher Shifts the Alphabet

Key = 11

Plainabcdefghijklmnopqrstuvwxyz
Cipherlmnopqrstuvwxyzabcdefghijk

Each letter maps to the letter below it

h e l l o   →   s p w w z

55

The Inputs Define the Encryption Task

plain_text = 'hello'key = 11print(plain_text)print(key)
Download: lec_04_caesar_inputs.py

plain_text
The text to transform

key
How far to shift each letter

Use lowercase English letters and a key from 0 to 25

56

Two Slices Rotate the Alphabet

plain_text = 'hello'key = 11alphabet = 'abcdefghijklmnopqrstuvwxyz'shifted = alphabet[key:] + alphabet[:key]print(alphabet)print(shifted)
Download: lec_04_caesar_alphabet.py

alphabet[11:]
lmnopqrstuvwxyz

alphabet[:11]
abcdefghijk

Join the suffix and prefix

57

A Loop Builds the Cipher Text

plain_text = 'hello'key = 11alphabet = 'abcdefghijklmnopqrstuvwxyz'shifted = alphabet[key:] + alphabet[:key]cipher_text = ''for char in plain_text:    index = ord(char) - ord('a')    cipher_text += shifted[index]print(cipher_text)
Download: lec_04_caesar_encrypt.py
VariableValue
char'h'
index7
shifted[index]'s'
cipher_text's'
VariableValue
char'e'
index4
shifted[index]'p'
cipher_text'sp'
VariableValue
char'l'
index11
shifted[index]'w'
cipher_text'spw'
VariableValue
char'l'
index11
shifted[index]'w'
cipher_text'spww'
VariableValue
char'o'
index14
shifted[index]'z'
cipher_text'spwwz'
58

Trying All 26 Keys

alphabet = 'abcdefghijklmnopqrstuvwxyz'cipher_text = 'spwwz'for key in range(26):    shifted = alphabet[-key:] + alphabet[:-key]    plain_text = ''    for char in cipher_text:        plain_text += shifted[ord(char) - ord('a')]    print(f'{key:02}:{plain_text}', end='  ')
Download: lec_04_caesar_attack.py
59

A Loop Can Collect Names

names = []while True:    new_name = input('Name (blank ends): ')    if new_name == '':        break    names.append(new_name)    print(names)
Download: lec_04_collect_names.py
60

Each Insertion Keeps the List Sorted

names = []for new_name in ['HKU', 'CUHK', 'HKUST']:    pos = 0    while pos < len(names):        if names[pos] > new_name:            break        pos += 1    names.insert(pos, new_name)    print(names)
Download: lec_04_sorted_insertion.py

Find the first name that is greater than the new name

Insert immediately before it

If none is greater, insert at the end

61

The First Name Enters an Empty List

names = []for new_name in ['HKU', 'CUHK', 'HKUST']:    pos = 0    while pos < len(names):        if names[pos] > new_name:            break        pos += 1    names.insert(pos, new_name)    print(names)
Download: lec_04_sorted_insertion.py

New name: 'HKU'

pos = 0

 
Empty list

Begin with an empty list

New name: 'HKU'

pos = 0

 
Empty list

0 < 0 is False

New name: 'HKU'

pos = 0

 
Empty list

Skip the while body

New name: 'HKU'

pos = 0

0
HKU

Insert at position 0

New name: 'HKU'

pos = 0

0
HKU

Print the updated list

62

A Smaller Name Goes Before HKU

names = []for new_name in ['HKU', 'CUHK', 'HKUST']:    pos = 0    while pos < len(names):        if names[pos] > new_name:            break        pos += 1    names.insert(pos, new_name)    print(names)
Download: lec_04_sorted_insertion.py

New name: 'CUHK'

pos = 0

0
HKU

Begin the next iteration

New name: 'CUHK'

pos = 0

0
HKU

0 < 1 is True

New name: 'CUHK'

pos = 0

0
HKU

'HKU' > 'CUHK' is True

New name: 'CUHK'

pos = 0

0
HKU

break leaves the while loop

New name: 'CUHK'

pos = 0

01
CUHKHKU

Insert before HKU

New name: 'CUHK'

pos = 0

01
CUHKHKU

Print the updated list

63

A Larger Name Goes at the End

names = []for new_name in ['HKU', 'CUHK', 'HKUST']:    pos = 0    while pos < len(names):        if names[pos] > new_name:            break        pos += 1    names.insert(pos, new_name)    print(names)
Download: lec_04_sorted_insertion.py

New name: 'HKUST'

pos = 0

01
CUHKHKU

Reset pos for the new name

New name: 'HKUST'

pos = 0

01
CUHKHKU

0 < 2 is True

New name: 'HKUST'

pos = 0

01
CUHKHKU

'CUHK' > 'HKUST' is False

New name: 'HKUST'

pos = 1

01
CUHKHKU

Advance to the next position

New name: 'HKUST'

pos = 1

01
CUHKHKU

1 < 2 is True

New name: 'HKUST'

pos = 1

01
CUHKHKU

'HKU' > 'HKUST' is False

New name: 'HKUST'

pos = 2

01
CUHKHKU

Advance again

New name: 'HKUST'

pos = 2

01
CUHKHKU

2 < 2 is False

New name: 'HKUST'

pos = 2

012
CUHKHKUHKUST

Insert at the end

New name: 'HKUST'

pos = 2

012
CUHKHKUHKUST

Print the updated list

64

sorted Returns a New Sorted List

names = []for new_name in ['HKU', 'CUHK', 'HKUST']:    names.append(new_name)ordered = sorted(names)print(ordered)print(names)
Download: lec_04_builtin_sorted.py
65

Working with Strings

SelectIndex, slice, or iterate
CheckCompare, search, or test characters
ConstructConcatenate, join, or replace
PresentFormat values with f-strings

A string operation can return a new value
without changing the original string

66

Complete the full survey during the lecture

67

Coding Challenge

Work independently on the L-4 challenges in Ed

68