0% found this document useful (0 votes)
9 views11 pages

Lec 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

Lec 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

STRINGS

Sequence of case-sensitive characters


◦ Denoted inside quotation marks: '…' or "…"
◦ Multiline strings: """…"""
◦ Empty string: '' or ""

Compare with: ==, !=, <, >, <=, >=


Function len() retrieves the length of the string
s = ‘abc’
len(s) ➔ evaluates to 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

Figure 7.1 Forward


The stringindex:
"Python rules!"
from 0 toand the index of each character. The
len(s)-1
first row shows indexing
s[0] ➔ with
'P'positive integers, and the second row shows
indexing with negative
s[1] integers.
➔ 'y' Backward index: from -1 to -len(s)
s[2] ➔ 't' s[-1] ➔ '!'
s[6] ➔ ' ' s[-2] ➔ 's'
s[12] ➔ '!' s[-3] ➔ 'e'
s[-7] ➔ ' '
Convert from/to [-i] = [len(s) - i] s[-13] ➔ 'P'
forward/backward 2
◼︎
◼︎
STRING SLICING

Slice: a (not necessarily consecutive) portion of a


string (substring)
Slicing: extract a slice enclosed between given indices

[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]

Index of the rst How many


character to take characters to skip
Index up to which to take, > 0: left-to-right
but not including the < 0: right-to-left
character at stop_index
Defaults: Copy of s
step s = '...'
s[::] == s[0:len(s):1] == s[:]
>0 <0
s[::-1] == s[-1:-(len(s)+1):-1]
start_index 0 -1 s[:5:] == s[0:5:1]
stop_index len -(len + 1) s[6::-2] == s[6:-(len(s)+1):-2]
step 1 s[:-6:2] == s[0:len(s)-6:2]
Reversed copy of s
4
fi
third character, starting with the one at index 2 and not including the one at
index 11.

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'

s.lower(): convert all letters to the lowercase


◦ s.lower() ➔ 'python is cool'

s.swapcase(): swap lower to upper and vice versa


◦ s.swapcase() ➔ 'PYTHON IS cOOL'

s.capitlize(): convert the first character to a capital


letter and makes the rest of the letters lowercase
◦ s.capitlize() ➔ '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

s.rfind(t): the starting index of the first occurrence of t nearest to


the end of s; -1 if not found
◦ s.rfind('on') ➔ 10

s.count(t): the number of occurrences of t in s


◦ s.count('on') ➔ 2

s.replace(t, u): evaluates to the result of replacing all


occurrences of t with u
◦ s.replace('on', 'off') ➔ 'Pythoff is off'

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

Both code fragments do the same thing


Bottom one is more "pythonic"
s = 'Python is cool'
for i in range(len(s)):
if s[i] == 'P' or s[i] == 'o':
print("There is a 'P' or an 'o'")

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

You might also like