Lec 3
Lec 3
1
◼︎
◼︎
◼︎
n computer science, you start counting from 0. This is used when you manipulate
ring objects. Take a look at figure 7.1, which shows a string object whose value is
STRING INDEXING
ython rules!" Each character is located at an index. The first character in a string is
ways at index 0. For the string "Python rules!", the last character is at index 12.
ou can also count backward. The last character in any string is always at index -1 when
Retrieve the value of character at a given index
ou’re counting backward. For the string "Python rules!", the first character, P, is at index -13.
Use
otice that the square
space is also abrackets:
character. []
s = " P y t h o n r u l e s ! "
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
–13 –12 –11 –10 –9 –8 –7 –6 –5 –4 –3 –2 –1
[start_index:stop_index]
[start_index:stop_index:step]
How many
Index of the rst characters to skip
character to take > 0: left-to-right
Index up to which to take,
< 0: right-to-left
but not including the
Optional, default = 1
character at stop_index
3
◼︎
◼︎
fi
STRING SLICING
[start_index:stop_index:step]
STRING SLICING
cheer[-2:-11:-3] evaluates to 'sun' because you’re stepping right to left, taking
every third character, starting with the one at index -2 and not including the one
at index -11.
P y t h o n r u l e s !
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
–13 –12 –11 –10 –9 –8 –7 –6 –5 –4 –3 –2 –1
[2:7:1] 1 2 3 4 5
[2:11:3] 1 2 3
[-2:-11:-3] 3 2 1
[8:] 1 2 3 4 5
Figure 7.2 Three examples of slicing into the string “Python rules!”. The numbered
circles
[-3::]on each row indicate the order in which Python retrieves the characters
1 2 from
3
the string to form a10new substring from the slice.
[-3::-1] 11 9 8 7 6 5 4 3 2 1
[:9:-2] 2 1
5
USEFUL STRING COMMANDS
s = 'python is Cool'
len(s): length of the string (built-in function)
◦ len(s) ➔ 14
t in s: test if string t is in s
◦ 'is' in s ➔ True
◦ 'n' in s ➔ True
◦ 'cool' in s ➔ False
6
◼︎
◼︎
USEFUL STRING COMMANDS
s = 'python is Cool'
s.upper(): convert all letters to the uppercase
◦ s.upper() ➔ 'PYTHON IS COOL'
7
◼︎
◼︎
◼︎
◼︎
USEFUL STRING COMMANDS
s = 'Python is on'
s.find(t): the starting index of the first occurrence of string t in s;
-1 if not found
◦ s.find('tho') ➔ 2
8
◼︎
◼︎
◼︎
◼︎
STRING MUTABILITY
STRINGS
Strings are immutable: cannot be modified in place
sstrings are “immutable” – cannot be modified
= 'hello'
s = "hello"
s[0] = 'y' ➔ Error!
s[0] = 'y' gives an error
s = 'y'+s[1:len(s)] is allowed,
s bound to new object
s = 'hello'
"hello"
s = 'y' + s[1:]
"yello" Bind s to a new
s
string object
6.0001 LECTURE 3 7
9
◼︎
STRINGS AND for LOOPS
s = 'Python is cool'
for char in s:
if char == 'P' or char == 'o':
print("There is a 'P' or an 'o'")
10
◼︎
◼︎
CODE EXAMPLE
word = 'Python'
an_letters = 'aefhilmnorsxAEFHILMNORSX'
i = 0
while i < len(word): for ch in word
ch = word[i]
if ch in an_letters:
print("Give me an " + ch + "! " + ch)
else:
print("Give me a " + ch + "! " + ch)
i += 1
11