Introduction to Computing –
Python (IS086IU)
Chapter 6: Strings and String Functions
Nguyen Minh Thien
Tran Minh Hieu
Vuong Quoc Bao
Nguyen Trung Luong
2025 – 2026
String literals and operations
Escape Sequences
Overview Indexing and Slicing
String methods
Formatting string
2
1. String Literals and operations
• Python string are categorized as immutable
sequences.
• The characters they contain have a left-to-right
positional order that cannot be changed in-place.
WHAT FOR?
• Used to represent just about anything that can be
encoded as text: symbols and words, contents of text
files loaded into memory, Internet addresses ….
• Hold binary values of bytes and multibytes
3
Operation Interpretation
S = "" Empty string
S = "The house’s" Double quotes, same as single
S = 's\np\ta\xOOm' Escape sequences
S = """……""" Triple-quoted block strings
S1+S2 Concatenate
1.1 Common
S*3 Repeat
S[i] Index
Slice
String Literals
S[i:j]
Len(S) Length
“a {0} String format expression
& operations
parrot“.format(kind)
[Link]('pa') String method calls: search
[Link]() Remove whitespace
[Link]('pa','xx') Replacement
[Link](',') Split on delimiter
[Link]() Content test
[Link]() Case conversion
[Link]('spam') End test
4
1.2 Escape Sequences
Represent Special Bytes
• A special byte can be inserted inside a
string known as escape sequences.
• An escape sequence is embedded after
the character \
• For example: This string contains 5
character: ‘a’, newline, ‘b’, horizontal tab
and ‘c’
5
Output Comment
len('abcd') 4
'abc' + 'def' 'abcdef'
'ab3' * 4 ab3ab3ab3
myjob = "hacker“ hacker c becomes a cursor
for c in myjob: stepping across the
string
1.3 Basic
print(c,end = ' ')
Operations check1 = "k" in myjob True
False
Example
check2 = "d" in myjob
text = 'abcdspamdef’ True No position returned
check3 = 'spam' in
'abcdspamdef'
6
1.4 Indexing & Slicing
Indexing (S[i]) fetches components at offsets:
— The first item is at offset 0.
— Negative indexes mean to count backward from the end or right.
— S[0] fetches the first item.
— S[-2] fetches the second item from the end (like S[len(S)-2])
Slicing (S[i]) extracts contiguous sections of sequences:
— The upper bound is noninclusive.
— Slice boundaries default to 0 and the sequence length, if omitted.
— S[1:3] fetches items at offsets 1 up to but not including 3.
— S[1:] fetches items at offset 1 through the end (the sequence length).
— S[:3] fetches items at offset 0 up to but not including 3.
— S[:-1] fetches items at offset 0 up to but not including the last item.
— S[:] fetches items at offsets 0 through the end—
this effectively performs a toplevel copy of S
7
1.4 Indexing & Slicing
Extended slicing
Slicing expression have support third index, used as a step
X[I:J:K]
Means: Extract all the items in X from offset I through J-1 by K
Examples:
Output Comment
S = 'abcdefghijklmnop’ 'bdfhj' Extract the characters
S[1:10:2] indexed 1 3 5 7 9
S[::2] 'acegikmo'
S = 'hello' 'olleh' reverse the sequence
S[::-1]
S = 'abcedfg' 'fdec' fetches the items from 2
S[5:1:-1] to 5, in reverse order
(the result
contains items from
offsets 5, 4, 3, and 2
8
1.5 Changing Strings
Output Comment
S = 'spam' Error String is immutable sequence
S[0] = "x"
S = S + 'SPAM!' 'spamSPAM!' To change a string, make a new one
S = S[:4] + 'Burger' + S[-1] 'spamBurger!' replaces four characters with six
S by slicing, indexing, and
concatenating
S = 'splot' 'spamalot' similar effects with
S = [Link]('pl', 'pamal’) string method calls like replace
9
[Link]() Capitalizes only the first character.
[Link](width, fill) Centers string using fill char to meet width.
[Link](sub) Returns count of substring sub occurrences.
[Link](suffix) Checks if string ends with suffix.
[Link]() Replaces tabs (’t’) with spaces.
2. String methods [Link](sub)
[Link](...)
Returns lowest index of sub (-1 if not found).
Performs value insertion using format specifiers.
Returns lowest index of sub (raises error if not
[Link](sub) found).
[Link]() Checks if all chars are alphanumeric.
[Link]() Checks if all chars are alphabetic.
[Link]() Checks if all chars are base 10 digits.
[Link]() Checks if all chars are digits (0-9).
[Link](width, fill) Left-justifies string using fill char.
[Link]() Converts all chars to lowercase.
• Strings provide a set of methods that implement more Removes leading (left) specified
sophisticated text-processing tasks. [Link](chars) characters/whitespace.
[Link](sep) Splits into three parts at the first sep.
• Methods are simply functions that are associated with
particular objects. [Link](old, new) Replaces all old substrings with new.
[Link](sub) Returns highest index of sub (-1 if not found).
• Technically, they are attributes attached to objects Returns highest index of sub (raises error if not
that happen to reference callable functions [Link](sub) found).
More string methods — Python 3.14.0 documentation [Link](width, fill) Right-justifies string using fill char.
[Link](sep) Splits string from the right.
Removes trailing (right) specified
[Link](chars) characters/whitespace.
Splits string from the left by sep (default
[Link](sep) whitespace).
10
2.1 String method examples – Changing Strings
Output Comment
S = 'spammy' 'spaxxy' Replace two characters in the string
S = [Link]('mm', 'xx')
'aa$bb$cc$dd'.replace('$', 'SPAM') 'aaSPAMbbSPAMccSPAMdd' Takes as arguments the
original substring (of any length) and the
string (of any length) to replace it with, and
performs a global search and replace
S = 'xxxxSPAMxxxxSPAMxxxx' 4 Search for position
where = [Link]('SPAM') Occurs at offset 4
[Link]('SPAM', 'EGGS’) 'xxxxEGGSxxxxEGGSxxxx’ #Replace all SPAM by EGGS
[Link]('SPAM', 'EGGS', 1) 'xxxxEGGSxxxxSPAMxxxx' #Relace one
11
2.2 String method examples – Parsing Text
Output Comment
line = 'aaa bbb ccc' ['aaa', 'bbb', 'ccc'] The string split method chops up a string into a
cols = [Link]() list of substrings, around a delimiter string
cols (Whitespace by default)
line = 'bob,hacker,40' ['bob', 'hacker', '40'] Delimiter is a comma
[Link](',')
line = "i'mSPAMaSPAMlumberjack" ["i'm", 'a', 'lumberjack'] Delimiters can be longer than a single character.
[Link]("SPAM")
line = "The knights who say Ni!\n" 'The knights who say Ni!' to strip off whitespace at the end of a line of text
[Link]()
[Link]() False #True if all the characters are alphabet letters (a-z).
[Link]('Ni!\n') True #Check if the string ends with 'Ni!\n’
[Link]('The') True #Check if the string starts with The'
You can also check the help([Link]) results for a method of any string object S for more hints.
12
In-Class Exercise
You are given with a list of Product IDs as follows: Product ID string structured as follows:
product_id1 = "ELC-HCM-00113390-DM“ [Type]-[Location]-[Serial]-[Status]
product_id2 = “FAB-HCM-00321567-OK“
product_id3 = “PAP-HAN-00221570-OK“ Type: ELC: Electronics; FAB: Food; PAP: Paper
product_id4 = “PAP-HAN-00525590-DM“ Location: HCM: HoChiMinh; HAN: HaNoi;
product_id5 = "ELC-HCM-00821770-OK“ Status: OK: Good; DM: Damaged
product_id6 = “FAB-HAN-00812150-DM“
product_id7 = "ELC-HCM-00121440-DM"
Build a Python program to:
a. Remove the first two zeros in serial numbers.
b. Print the damaged Electronics product IDs with new serial numbers
Example output:
--- Damaged Electronics Report ---
Damaged ELC Found: ELC-HCM-113390-DM
Damaged ELC Found: ELC-HCM-121440-DM
13
3. String Formating Expression
- Formating is the way we decide how a string to be displayed.
- String formatting allows us to perform multiple type-specific substitutions on a string in a single step.
- Very convenient, especially when formatting text to be displayed to a program’s users.
▪ Use the format()method on a template string
containing {}.
▪ Provide values to insert as the method's
arguments.
▪ Reference placeholders by their index {0} or a
keyword {item}
14
3.1 String Formating Expression
Output Comment
template = '{0}, {1} and {2}’ 'spam, ham and eggs' #By position
[Link]('spam', 'ham', 'eggs')
template = '{motto}, {pork} and {food}’ 'spam, ham and eggs' #By keyword
[Link](motto='spam',
pork='ham', food='eggs')
template = '{motto}, {0} and {food}’ 'spam, ham and eggs’ #By both
[Link]('ham', motto='spam',
food='eggs')
X = '{motto}, {0} and {food}'.format(42, '3.14, 42 and [1, 2]' format really must make a new
motto=3.14, food=[1, 2]) object string, can be save for
future work
[Link](' and ') ['3.14, 42', '[1, 2]'] Split using delimiter ‘and’
Y = [Link]('and’, but') '3.14, 42 but [1, 2]'
15
3.1 String Formating Expression
Output Comment
somelist =list('SPAM’)
somelist ['S', 'P', 'A', 'M'] # a list is
'first={first},third={third}'.format(first=somelist[0], 'first=S, third=A' created
third=somelist[2])
'first={0}, last={1}'.format(somelist[0], somelist[-1]) 'first=S, last=M' Format strings
can name list
offsets to
perform
indexing
parts = somelist[0], somelist[-1], somelist[1:3] "first=S, last=M, middle=['P', 'A']"
'first={0}, last={1}, middle={2}'.format(*parts)
16
3.2 Adding Specific Formatting
Output Comment
'{0:10} = {1:10}'.format('spam', 123.4567) 'spam = 123.457' {0:10} means the first positional
argument in a field 10 characters wide
'{0:>10} = {1:<10}'.format('spam', 123.4567) ' spam = 123.457 ' {1:<10} means the second positional
argument left-justified in a 10-character-
wide field
'{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, '3.141590e+00, {2:g} means the third argument formatted
3.14159) 3.142e+00, 3.14159' by default according to the “g” floating-
point representation
'{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, '3.141590, 3.14, 003.14' {1:.2f} designates the “f” floating-point
3.14159) format with just 2 decimal digits
{2:06.2f} adds a field with a width of 6
characters and zero padding on the left
17
Self-test questions
1. Can the string find method be used to search a list?
2. Can a string slice expression be used on a list?
3. How might you go about changing a string in Python?
4. How many characters are there in the string "a\nb\x1f\000d"?
5. Given a string S with the value "s,pa,m", name two ways to extract the two
characters in the middle ‘pa’.
18
Thanks for listening!
19