Cs100 2014F Lecture 05 String Methods
Cs100 2014F Lecture 05 String Methods
Strings, revisited
Objects and their methods
Indexing and slicing
Some commonly used string methods
Slicing a string
You can use indexes to slice a string
aStr[i:j] is the substring that begins with index
i and ends with (but does not include) index j
>>> greeting = 'hello, world'
>>> greeting[1:3]
'el'
>>> greeting[-3:-1]
'rl'
SAME:
You can index a list (or tuple), beginning
with 0 from the left or -1 from the right.
You can slice a list using begin and end
([i:j]) or begin, end and step ([i:j:k])
You can omit begin or end ([:j] or [i:]) to
mean 'as far as you can go'
DIFFERENT:
if you take a single element of a list with
the index operator ([i]), its type is the type
of that element
>>> abc = ['a', 'b', 'c']
>>> abc[0]
'a'
>>> type(abc[0])
<class 'str'>
String methods
A method is a function that is bundled
together with a particular type of object
A string method is a function that works on a
string object
This is the syntax of a method:
anObject.methodName(parameterList)
For example,
>>> 'avocado'.index('a')
0
Method parameters
Like any function, a method may have zero or
more parameters
Even if the parameter list is empty, the
method still works on the 'calling' object:
>>> 's'.isupper()
False
aStr =
newStr
newStr
dog is
aStr
cat is