Strings Indexing, Length, and Traversal
Explore string fundamentals in Python, including zero-based and negative indexing, length calculation, and various traversal methods. Understand how to access characters by position, handle index boundaries, and iterate over strings effectively to prepare for string algorithm challenges.
We'll cover the following...
By now, you know that a string is an ordered sequence of characters stored contiguously in memory and that its structure is essentially identical to an array. It is a clean and simple idea, but an idea alone does not help you solve problems. The real question is how you actually work with a string once you have one. How do you reach into it and pull out a specific character? How do you know how many characters it contains? How do you move through it one step at a time? These are the basic operations that every string algorithm depends on, and getting comfortable with them is what turns the conceptual picture of strings into something you can actually use.
Indexing in strings
Each character in the string is associated with a specific position called an index. Indexing starts at zero, meaning the first character is at index 0, the second is at index 1, the third is at index 2, and so on. This is the same zero-based indexing that arrays use.
Accessing individual characters
Because a string is stored like an array, accessing an individual character works exactly the same way as accessing an element in an array. To retrieve a character at a specific index, write the name of the string followed by the index in square brackets.
The result of indexing into a string is always a single character. This operation takes constant time
Negative indexing
Python offers something that lower-level languages like C do not: the ability to index from the end of a string using negative numbers. An index of -1 refers to the last character, -2 refers to the second-to-last, and so on.
Negative indexing is not just a syntactic convenience. It is genuinely useful in practice. Many string problems require looking at the last character or working backward from the end, and negative indices make that code cleaner and easier to read. The alternative, writing s[len(s) - 1] every time you need the last character, is verbose and harder to follow at a glance. ...