PythonPython StringsPython string indexing
How do you access individual characters in a string?
Question 62 of 88 · Updated
On this page
- 1. Accessing a string by position
- 2. How negative indexing works
- 3. What exactly is a character in Python?
- 4. Iterating through individual elements
- 5. IndexError and TypeError
- 6. Safe access when a character may be missing
- 7. The integer-index protocol
- 8. Practical example: reading a fixed-format prefix
- 9. String indexing versus bytes indexing
- 10. Time and memory considerations
- 11. Common mistakes
- Frequently asked questions
- How do you get the first character?
- How do you get the last character?
- Does an out-of-range string index return None?
- What is the difference between indexing and slicing?
- Can I use a float as a string index?
- Interview-ready answer
- Official references
Access an individual element of a Python string using square brackets and an integer index, such as s[0] for the first element or s[-1] for the last. The operation returns a str of length one, representing one Unicode code point.
Indexing is a fundamental sequence operation. This lesson explains valid positions, negative indexes, boundaries, Unicode behavior and safe access. The earlier string introduction covered the text model; the upcoming slicing lesson covers selecting ranges of positions.
1. Accessing a string by position#
PYTHONs = 'Python' print(s[0], s[2], s[-1], s[-6])
Output:
P t n PPython uses zero-based indexing: the first element is at index zero, not one. Negative indexes count backward from the end, with -1 selecting the last element.
| Code point | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
The two index systems identify the same positions. For example, s[0] and s[-6] both select P.
The square brackets are Python's subscription syntax. They do not call a string method or modify the string.
2. How negative indexing works#
For a string of length n and a negative index i, the equivalent nonnegative position is n + i. For nonnegative i, the position is simply i.
For a nonempty string, the valid original integer indexes satisfy:
-n <= i < nWith six code points, the valid negative indexes run from -6 through -1, and the valid nonnegative indexes run from 0 through 5.
The diagram shows the conceptual interpretation of an already valid integer index. It does not require a particular interpreter implementation.
Negative indexing is not circular indexing. An excessively negative index does not repeatedly wrap around to a valid position. Also, -0 equals 0, so s[-0] selects the first element rather than the last.
An empty string has no valid individual position, positive or negative.
3. What exactly is a character in Python?#
PYTHONs = 'Aé🙂' print([(c, ord(c)) for c in s]) print(type(s[1]).__name__, len(s[1]))
Output:
[('A', 65), ('é', 233), ('🙂', 128578)]
str 1Python does not define a separate built-in char type. The indexed value is a string containing one Unicode code point. The ord function returns the numerical code point of a one-code-point string.
This is different from selecting a visually perceived character. A letter with a combining accent, a flag emoji or an emoji with a skin-tone modifier may contain multiple code points. Indexing may select only one part of such a sequence.
For example, a decomposed e followed by U+0301 occupies two positions. Index zero selects e; index one selects the combining accent. A graphical interface may display those two code points together as one grapheme cluster.
The earlier Unicode lesson explains canonical normalization. Normalization can help with equivalent representations but does not turn every grapheme cluster into one code point. Use an appropriate Unicode segmentation policy if the task requires selecting entire user-perceived characters.
4. Iterating through individual elements#
PYTHONs = 'ab' for i, ch in enumerate(s): print(i, ch)
Output:
0 a
1 bWhen every element is needed, ordinary string iteration is usually simpler than manually maintaining an index. If both the position and element matter, enumerate supplies both.
Use direct subscription when a specific position is required. Use iteration when the task involves processing the complete text.
Neither direct iteration nor enumerate creates a full list of all code points by itself. Calling list(s) is unnecessary for ordinary indexed access or traversal.
5. IndexError and TypeError#
An individual index must refer to an existing position. Invalid positions are not automatically clamped to the nearest available element.
| Expression | Result |
|---|---|
'cat'[3] | IndexError: past the last position |
'cat'[-4] | IndexError: before the first position |
''[0] | IndexError: no element exists |
'cat'[1.0] | TypeError: float is not an integer index |
'cat'['1'] | TypeError: string is not an integer index |
The five expected exception types were verified on the local Python runtime. CPython 3.13 also emitted SyntaxWarning for the statically recognizable float and string index examples. Such warnings do not make those subscriptions valid.
A float with an integer-valued magnitude, such as 1.0, is not accepted as an ordinary string index. Nor does Python automatically convert the text '1' to the integer 1. Parse or validate external index inputs according to the application's requirements.
Do not confuse an out-of-range index with an empty result. Indexing raises IndexError, while a slice can return an empty string. Slicing has its own boundary rules and is covered separately.
6. Safe access when a character may be missing#
Sometimes a missing position is expected rather than exceptional. A helper can explicitly return None for that case.
PYTHONdef char_at(text, index): if not isinstance(text, str): raise TypeError('expected text') if not isinstance(index, int) or isinstance(index, bool): raise TypeError('expected integer index') if -len(text) <= index < len(text): return text[index] return None print(char_at('cat', -1), char_at('', 0), char_at('cat', 3))
Output:
t None NoneThe function checks the complete valid index interval. That interval is empty when len(text) is zero.
It intentionally defines a narrower input contract than Python's native subscription operation: the caller must supply an int or an int subclass other than bool. It does not accept arbitrary objects that implement the integer-index protocol.
The None result is distinguishable from every successful result, because native string indexing returns a string of length one. The helper does not hide type errors or unrelated application failures.
In a context where an invalid position indicates a programming mistake, allowing IndexError to propagate may be better than substituting a default value. Choose the failure behavior deliberately.
7. The integer-index protocol#
Python accepts appropriate integer-like objects through the special method __index__.
PYTHONclass Position: def __index__(self): return -2 print('Python'[Position()])
Output:
oThe Position object supplies the integer -2. Python uses that value to select the second-to-last code point.
The __index__ method represents a lossless integer interpretation for operations requiring exact integers. A class that merely implements __int__ is not necessarily valid for indexing.
Boolean values are also accepted by native string indexing because bool is a subclass of int: False behaves as zero and True as one. Although valid, using a Boolean index is usually less clear than explicitly expressing the intended position. An API can reject Boolean values when they would be misleading, as the previous helper does.
8. Practical example: reading a fixed-format prefix#
Suppose a simple task record begins with the letter P followed by an ASCII digit indicating priority, such as P3:review. The following function validates the two-code-point prefix and extracts the digit.
PYTHONdef priority(record): if len(record) < 2 or record[0] != 'P' or record[1] not in '0123456789': raise ValueError('invalid priority prefix') return int(record[1]) print(priority('P3:review')) try: priority('P') except ValueError as exc: print(exc)
Output:
3
invalid priority prefixThe first condition checks the length before accessing either position. Python's or operator short-circuits, so a record shorter than two code points does not cause an out-of-range access.
The digit test deliberately accepts only the ten ASCII digit characters. It does not accept every character that Unicode classifies as a digit. This is appropriate for a fixed ASCII prefix contract, not a universal numerical-text validator.
The function assumes the record is a str and validates only the first two positions. It does not validate the separator, the remaining record body or a complete file format. A production parser should enforce its full documented grammar.
For a fixed prefix, positional access is clear. For variable-width fields or formats with separators, splitting or a dedicated parser may be more appropriate.
9. String indexing versus bytes indexing#
PYTHONtext = 'é' raw = text.encode('utf-8') print(text[0], raw[0], raw[1]) print(type(raw[0]).__name__)
Output:
é 195 169
intThe text is one Unicode code point. Its UTF-8 representation consists of two bytes, with decimal values 195 and 169. Accessing a position in a bytes object returns an integer rather than a one-code-point string.
Do not apply byte offsets directly to a decoded Unicode string. Byte offsets, code-point indexes and grapheme-cluster positions can all differ.
For example, if a network protocol defines offsets in UTF-8 bytes, interpret those offsets in the encoded representation according to that protocol. If a user-interface operation refers to displayed text elements, a grapheme-aware policy may be needed instead.
10. Time and memory considerations#
For ordinary CPython str objects, retrieving a valid integer position is typically constant-time under the usual bounded-size index model. The implementation can locate a code point directly using its internal representation. Python's language specification does not promise a particular asymptotic runtime or memory layout for all implementations.
Traversing all n code points requires O(n) iteration steps, excluding the cost of the loop body. Accessing one position does not require building a full character list.
The returned value is a string of length one. An interpreter may reuse existing immutable objects where appropriate; do not assume a fresh allocation or rely on object identity. Compare text values using equality.
If the objective is to extract k contiguous elements, use an appropriate slice rather than repeatedly indexing and concatenating single-code-point strings. The next lesson examines slice semantics and their costs.
11. Common mistakes#
| Mistake | Correct approach |
|---|---|
| Treating index 1 as the first position | Use index 0 |
| Using len(s) as the last index | Use len(s) - 1 or -1 for a nonempty string |
| Assuming negative indexes wrap indefinitely | Check the valid index range |
| Indexing an empty string | Handle the empty case first |
| Assuming one code point is always one displayed character | Use grapheme-aware processing when required |
| Using byte offsets on str | Match the offset units to the representation |
| Converting an entire string to a list just to access one position | Index the string directly |
Strings are immutable, so assigning to an indexed position is not supported. Obtain a replacement string when a different textual value is required. That behavior was already covered in the immutability and string foundations lessons.
Frequently asked questions#
How do you get the first character?#
Use s[0] after ensuring the string is nonempty.
How do you get the last character?#
Use s[-1] for a nonempty string. The equivalent nonnegative index is len(s) - 1.
Does an out-of-range string index return None?#
No. Native string indexing raises IndexError. A wrapper can define a None-returning policy when that behavior suits the application.
What is the difference between indexing and slicing?#
Indexing selects a single position and returns a one-code-point string. Slicing selects a subsequence using a start, stop and optional step, with different rules for out-of-range bounds.
Can I use a float as a string index?#
No. Use an integer or an object supported by the integer-index protocol. Validate or parse external input before indexing.
Interview-ready answer#
Individual elements of a Python string are accessed using zero-based square-bracket indexing. A positive index starts from the beginning, and a negative index counts from the end. For a string of length n, valid integer indexes satisfy -n <= i < n. An invalid position raises IndexError, while an unsupported index type raises TypeError. Each successful access returns a str of length one representing a Unicode code point, not necessarily a complete displayed grapheme cluster. Ordinary CPython string indexing typically takes constant time. Use enumerate when both positions and values are needed, and distinguish text indexes from encoded byte offsets.
Official references#
- Python Standard Library — Text Sequence Type: str
- Python Standard Library — Common Sequence Operations
- Python Language Reference — Subscriptions
- Python Tutorial — Text
- Python Language Reference — Emulating numeric types
- Python Unicode HOWTO
- PEP 393 — Flexible String Representation
Verification note: Seven runnable Python example groups matched their documented outputs in independent namespaces on CPython 3.13.5. Five expected-exception tests and 600 seeded randomized assertions comparing positive and negative indexes and list-based element access passed. The invalid float and string literal index tests also emitted SyntaxWarning on that runtime. The fenced Mermaid flowchart was manually reviewed; parser validation and public-site rendering were not performed because local Mermaid CLI and live web access were unavailable. Unicode grapheme segmentation was discussed conceptually, not tested using a third-party library. Official links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Standard Library — Text Sequence Type: strdocs.python.org
- 2.Python Language Reference — Subscriptionsdocs.python.org
- 3.Python Tutorial — Textdocs.python.org
- 4.Python Language Reference — Emulating numeric typesdocs.python.org
- 5.Python Unicode HOWTOdocs.python.org
- 6.PEP 393 — Flexible String Representationpeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design