Pick out characters by position, cut out slices, and see why string methods return new strings instead of changing the old one.
Python · beginner · 7 min · 8 steps · free
word = "python"
first = word[0]
last = word[-1]
middle = word[1:4] # from index 1 up to, not including, 4
length = len(word)
shout = word + "!" * 3
upper = word.upper() # a new string: the original never changes
print(first, last, middle, length, shout, upper, word)len counts the characters: 6.+ joins strings and * repeats one: "python!!!"..upper() returns a new string, "PYTHON". The original word is untouched.word is still "python" at the end. Indexing reads characters, slicing copies parts, and methods make new strings.word.upper() and expecting word itself to changelen(word) - 1Answer: "l". -1 is "o", so -2 is the "l" before it.
s = "hi"; s.upper(), what is s?Answer: "hi". The new "HI" was not saved anywhere; s is unchanged.
← Numbers and Arithmetic · String Methods: strip, split, join, replace →