Notes
A string is a sequence of characters. Each character has an index starting at 0.
word = "python"
print(word[0]) # p
print(word[-1]) # n
print(word[1:4]) # yth
print(len(word)) # 6
- Negative indexes count from the end. A slice
s[a:b]starts at index a and stops before b. +joins strings, and*repeats them:"ha" * 3is"hahaha".- Useful methods:
.upper(),.lower(),.replace("a", "b"),.strip(). - Strings are immutable: methods return a new string instead of changing the original.
Practice
With
s = "computer", what does print(s[2]) show?Indexing starts at 0: c is 0, o is 1, m is 2.
What does
print(len("hi there")) display?The string has 8 characters, including the space.
What does
print("Code".upper() + "!" * 2) display?.upper() gives "CODE", "!" * 2 is "!!", and joining gives "CODE!!".
Ready for more? Take the Unit 4 test.