str

Python's built-in immutable text type — a sequence of Unicode code points, not bytes.

                str(object='') -> str
              

Purpose

str represents text as a sequence of Unicode code points. It supports indexing, slicing, and iteration like other sequences, but — unlike list — it’s immutable: no operation changes a str object in place.

Example

word = "python"

print(word[0])       # "p"       — first character
print(word[-1])       # "n"       — last character
print(word[1:4])      # "yth"     — slice, end index excluded
print(word.upper())   # "PYTHON"  — returns a new str; word itself is unchanged
print(word.encode("utf-8"))  # b'python' — explicit conversion to bytes

Behavior notes

  • Every “modifying” method (.upper(), .replace(), .strip(), …) returns a new str; the original is never changed, because str is immutable.
  • Slicing s[start:stop] excludes stop — s[1:4] returns 3 characters, at indices 1, 2, and 3. Negative indices count from the end (s[-1] is the last character).
  • len(s) counts Unicode code points, which is not always the same number a person would count as “characters” for accented letters, emoji, or other composed symbols.
  • Converting to bytes (s.encode(encoding)) and back (b.decode(encoding)) is always explicit in Python 3 — there is no implicit mixing of str and bytes the way Python 2 allowed.

Common mistakes

  • Calling word.upper() and expecting word itself to have changed. It hasn’t — the result has to be captured (word = word.upper()) or used directly.
  • Assuming len(s) equals the number of bytes a string takes up when written to a file or sent over a network — for any non-ASCII text, encode it first and measure the bytes result instead.
  • Off-by-one slicing mistakes from forgetting that the stop index is excluded.

Implementation notes

That str is an immutable sequence of Unicode code points is a language guarantee. How CPython stores those code points in memory — a flexible representation that picks 1, 2, or 4 bytes per character depending on the widest code point actually present (see PEP 393) — is a CPython implementation detail, not something the language specifies or any other implementation is required to replicate.

Taught in these lessons

Related reference