Slicing and in
Sometimes you don't want the whole string — you want the first few characters, the last few, or just a middle chunk. Slicing lets you grab any part of a string by position. And the in operator lets you ask "does this text appear inside that text?"
Indexing: one character
Every character has a position called an index, starting at 0:
Python
Slicing: a range of characters
Use s[start:stop] to get characters from start up to but not including stop:
Python
You can leave either side blank to mean "the beginning" or "the end":
Python
The in operator
Use in to check whether one string appears inside another. It returns a boolean (True or False):
Python
This is handy in conditions:
Python
Key takeaways
- Indexing
s[i]gets one character; indexes start at0, and negatives count from the end. - Slicing
s[start:stop]includesstartbut excludesstop. - Leave a side blank for "beginning" (
s[:n]) or "end" (s[n:]). inreturnsTrue/Falsefor whether a substring appears — and it's case-sensitive.
No comments yet. Add the first comment to start the discussion.