Strings and Slicing
A string is a sequence of characters with a position. Indexing grabs one position; slicing grabs a run of them — the single most used trick in text work.
Indexing from the start
Positions start at 0. s[0] is the first character; negative numbers count back from the end.
Slicing: start : stop : step
The stop position is excluded — the slice ends just before it.
Where every index points
s[1:4] grabs yth — positions 1, 2 and 3, stopping before 4. Leaving a side blank means "as far as it goes": s[:3] starts at 0, s[3:] runs to the end.s[-1] is the last character and s[::-1] is the whole string backwards — the classic one-liner palindrome test.Strings and Slicing: A Practical Guide
Every text problem is, at bottom, "where does this thing start and where does it stop".
Quick Context
A string is immutable: you cannot change a character inside it, so operations never edit the original. Instead, they build a new string and hand it back — which is why "hello".upper() does not change the original, and why slicing returns a whole new string every time. This makes text manipulation safe to chain: each step is a pure transformation of the last.
Methods that read like English
Strings carry methods that are plain words: .upper() and .lower() rescale the case, .strip() removes surrounding whitespace, .replace() swaps one substring for another, .split() breaks a string into a list of pieces, and .find() locates a substring — returning -1 when it is not there. A string is a sequence of characters, but these methods are what make it feel like a language.
Interactive Exploration Guide
- Read the index outputs. In the first editor:
p, thenn(position 5), thennagain vias[-1], thentvias[-3]. - Count the slice. The second editor prints
yth— three characters from positions 1 through 3. Confirm for yourself that position 4 is never included. - Omit a side. Change
s[3:]tos[3:5]and run. Theodrops out because position 5 is excluded. Then trys[0:6:3]and read the spacing as "step over the characters two at a time". - Reverse it. Keep
s[::-1]and addprint(s[::-1] == s). That line is the entire palindrome check in one expression.
Key Takeaway
Strings are indexed sequences that start at 0, and slicing with start:stop:step reads a run out of them — with the stop position always excluded and negative indices counting from the end. Strings never change in place, so every operation returns a new string you can chain. Half of all text-processing code is slicing; the other half is the methods that read like English.