# CPSC120BFundamentals of Computer Science I

## Day 20 Notes

String Methods

### String Slice

• The index operator, [], copies a single character from a string

text = "banana"
print(text[0])
• But sometimes you want more than one character
• The slice operator lets you copy a sequence of characters
• It looks a lot like the index operator
• Just need to specify the start and end of the sequence

text = "banana"
print(text[1:3])
• Note, it the start index is inclusive and the end index is exclusive
• this is just like the range function
• Can also specify a step, just like the range function
• For you convenience, you can exclude the start or end index, which implies all the way to the end or beginning of the string

text = "banana"
print(text[1:])
print(text[:-1])

### String Methods

• Methods are functions that are called called on objects
• We’ve seen lots of them with turtle

a_turtle = turtle.Turtle()
a_turtle.forward(10)
• This is different than calling a function that we have written

go_forward(a_turtle, 10)
• A method call has an object (and a dot) before the method name
• Strings have methods

text = "banana"
print(text.upper())

### Strings are Immutable

• Strings are different than turtles in one very important way
• Strings are immutable, once a string is created it can’t be changed
• This is for efficiency reasons, if a string can’t be changed, the way it is represented in memory is more simple
• Turtles, on the other hand, can change, they change location, orientation, color, etc.
• So text.upper() does not change text

text = "banana"
text.upper()
print(text)
• Instead it creates a new string, and returns that

text = "banana"
print(text.upper())
print(text)
• Note, this does not mean that the string that a variable references can not be changed

text_1 = "banana"
text_2 = text_1
print(text_1, text_2)
text_1 = "mango"
print(text_1, text_2)
• This does not change “banana”, it changes what the variable references
• So the other string, is left unchanged
• This is the same behavior we have with ints, floats, and bools
• It’s also important to note what effect immutability has on function scope

def do_something(text):
text.upper()

text = "banana"
do_something(text)
print(text)