IntroStringMethodsH
IntroStringMethodsH
Methods Methods
Hard to appreci ate the reasons for thi s coupli ng
A speci al ki nd of functi on that i s very i mportant betw een data and methods so early i n the
to object-ori ented programmi ng i s called a course.
method.
For now , w e settle on getti ng used to the
In thi s style of programmi ng, there i s a ti ght speci al notati on that i s associ ated w i th the
coupli ng betw een structured data and the use of methods.
methods that w ork w i th that data.
We w i ll get i nto thi s topi c usi ng stri ngs.
count How many ti mes does stri ng t count How many ti mes does stri ng y
occur i n a stri ng s? occur i n a stri ng x?
There will be others later in the course. It would then be used like this: n = count(y,x)
1
1/22/2016
w e w i ll w rite
Once agai n, the ‘ dot” notati on
n = x.count(y)
s --> I T H - J F K - I T H s --> I T H - J F K - I T H
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10
m --> 2 m --> 0
s1.count(s2) the number of occurrences of string s2 in string s1 s1.count(s2) the number of occurrences of string s2 in string s1
Note, in general s1.count(s2) is not the same as s2.count(s1) Illegal: n = A.count(‘a’ or ‘e’ or ‘I’ or ‘o’ or ‘u’)
2
1/22/2016
‘ITH-JFK-ITH’ s --> I T H - J F K - I T H
find 3 0 1 2 3 4 5 6 7 8 9 10
‘-’
idx --> 4
It would then be used like this: n = find(y,x) s1.index(s2) the index of the first occurrence of string s2 in string s1
s1.find(s2)
s --> I T H - J F K - I T H
returns an i nt value that i s the i ndex of the
0 1 2 3 4 5 6 7 8 9 10 fi rst occurrence of stri ng s2 i n stri ng s1.
3
1/22/2016
x = s1 in s2 ‘ITH-JFK-ITH’
‘ITH’ replace ‘??-JFK-??’
x = s2.find(s1)>=0 ‘??’
s -> ‘one hundred and one’ s -> ‘one hundred and one’
s -> ‘one hundred and one’ s -> ‘one hundred and one’
t -> ‘one hundred and one’ t -> ‘seven hundred and seven’
No change if the character to be replaced is missing Replacing one substring with another
4
1/22/2016
s -> ‘one hundred and one’ returns a copy of the stri ng s i n w hi ch every
non- overlappi ng occurrence of the stri ng s1 i s
t -> ‘one hundred and one’ replaced by the stri ng s2.
Illegal!
s = ‘abcdefgh’
s[5] = ‘x’
s = ‘abcdefgh’
s = s[:5]+’x’+s[6:]
5
1/22/2016
specialChar = string.punctuation
alpha = string.letters
!"#$%&'()*+,./:;<=>?@[\]^_`{|}~
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
6
1/22/2016
1234567890
pi=3.1416 The “folder metaphor.
sqrt
The “dot” means “go i nsi de
and get thi s”