Learning outcomes
By the end of this chapter, you should be able to:- create and print strings
- use indexing and slicing
- apply basic string operators
- explain string immutability
30-minute recording plan
0-6 min: string creation and basics6-14 min: indexing and negative indexing14-22 min: slicing patterns and step22-27 min: operators on strings27-30 min: immutability and exam traps
Creating strings
Indexing
- first index is
0 - negative index counts from right side
Slicing
text[start:end:step]
Beginner alert: slice end is excluded
Intext[start:end], the end index is not included.
String operators
+for concatenation*for repetitioninfor membership tests
Operator-function map (MCQ-critical)
+-> concatenates two strings*-> repeats same string multiple times[]-> accesses one character by index[:]-> extracts slice/rangein-> membership check\-> escape character in string literal
Immutability
Strings cannot be changed in place.Useful basics
Advanced slicing trap (reverse-step puzzle)
With:zwtqnkheb on all 5 lines:
- all 5 slices traverse from near
zbackward by step-3 - each stop boundary is chosen so index
1('b') is last included char
Mini showcase: username cleanup
Exam-focused points
- indexing starts at
0 - negative index starts from end
- slice end index is excluded
- strings are immutable
- know operator-function mapping for
+,*,[],[:],in,\ - for negative step slices, start/stop direction is reversed
Practice questions
- Take a word and print first and last character.
- Reverse a string using slicing.
- Print every alternate character from a string.
- Match these:
+,*,[],[:],in,\- concatenation, repetition, indexing, slicing, membership, escape
