String Indexing and Slicing

Indexing reads one item from a sequence by its position. Python counts positions from 0, so "Python"[0] is "P" and "Python"[5] is "n". Negative positions count from the end, which avoids computing the length first: [-1] is the last character and [-2] the one before it.

Slicing reads a range. text[start:stop] includes start and excludes stop, so "orange"[1:4] is "ran" and the length of the result is stop - start when the step is 1 and 0 <= start <= stop <= len(text). Negative bounds are first interpreted relative to the end; a forward slice with its start after its stop is empty. Omitting a side uses the default: [:4] starts at the beginning and [4:] runs to the end. A third value sets the step, so [::2] takes every second character and [::-1] reverses the string. A zero step raises ValueError.

The two forms fail differently, which matters when input is irregular. An index outside the string raises IndexError, while a slice is clamped to the available range and simply returns what exists, so "abc"[1:99] is "bc" and a slice can return an empty string without any error. Code that trusts a slice to have a fixed length should check the length rather than assume it.

To locate text rather than count positions, use index(), which returns the position of the first occurrence and raises ValueError when the substring is absent, or find(), which returns -1 instead of raising. The in operator answers only whether a substring occurs. Cleaning values by fixed positions is fragile because one extra space shifts everything; prefer strip(), removeprefix(), and replace(), which express the intended transformation. They do not validate the input format: removing commas also turns malformed "5,00" into "500".

References: Common sequence operations, String methods. See it in use in Python Strings, Conditions, and Loops.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.