7. IntroStringMethods
7. IntroStringMethods
String Methods
Topics:
Methods and Data
More on Strings
Functions and Methods
The String Class
Data + Functions Together
“The square root of nine is three.”
The tone of this comment is that the
square root function can be applied to
numbers like nine.
‘ITH-JFK-ITH’
count 2
‘ITH’
we will write
n = x.count(y)
Methods: The Notation
>>> s =‘ITH-JFK-ITH’
>>> m = s.count(‘ITH’)
s --> I T H - J F K - I T H
0 1 2 3 4 5 6 7 8 9 10
m --> 2
>>> s =‘ITH-JFK-ITH’
>>> m = s.count(‘LGA’)
s --> I T H - J F K - I T H
0 1 2 3 4 5 6 7 8 9 10
m --> 0
s1.count(s2)
‘ITH-JFK-ITH’
find 3
‘-’
s --> I T H - J F K - I T H
0 1 2 3 4 5 6 7 8 9 10
idx --> 4
>>> s =‘ITH-JFK-ITH’
>>> idx = s.find(‘RFK’)
s --> I T H - J F K - I T H
0 1 2 3 4 5 6 7 8 9 10
idx --> -1
s1.find(s2)
s1 in s2
is a boolean-valued expression.
x = s1 in s2
x = s2.find(s1)>=0
Designing replace as a Function
‘ITH-JFK-ITH’
‘ITH’ replace ‘??-JFK-??’
‘??’
t -> ‘one-hundred-and-one’
t -> ‘onehundredandone’
The null string
has length 0.
s.replace(s1,s2)
s = ‘xxx’
t1 = s.replace(‘x’,‘o’)
t2 = s.replace(‘xx’,‘o’)
t3 = s.replace(‘xx’,‘oo’)
t1 -> ‘ooo’
t2 -> ‘ox’
t3 -> ‘oox’
replace does Not Replace
s = s.replace(s1,s2)
Illegal!
s = ‘abcdefgh’
s[5] = ‘x’
s = ‘abcdefgh’
s = s[:5]+’x’+s[6:]
Quickly Review Some
Other String Methods
The upper and lower Methods
islower()
isupper()
isalnum()
isalpha()
isdigit()
Boolean-Valued Methods
alpha = string.letters
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Useful String Constants
specialChar = string.punctuation
!"#$%&'()*+,./:;<=>?@[\]^_`{|}~
Useful String Constants
TheDigits = string.digits
1234567890
The “Dot” Notation--Again
math.sqrt
math.py math.pi