Home / Python Fundamentals

String Lab

Strings are immutable sequences of characters. Visualize indexing, slicing, and transformations in real-time.

Operations



Snippet


                    

String State

s = "..."
len: 8
Modify the base string or apply methods to see changes.

Logic Insight

Python strings are sequences of Unicode characters.

  • • Immutability: You cannot change a character in place. `s[0] = 'x'` is an error.
  • • Methods: String methods always return a new string object.
  • • Indexing: Negative indices count from the end (e.g., -1 is the last char).

Memory State

Immutability Check Passed

Strings in Python are pre-allocated and cached when short.

Overview

Strings are ordered and zero-indexed: text[0] is the first code point and text[-1] is the last. You cannot assign to one character, so text[0] = "H" raises TypeError. A transformation such as .upper() returns a new string.

Immutability and indexing

Use Base String and Method in the visualizer, then press Apply Transformation. Compare the original with the result. Try Start, Stop, and Step with the Slicing method: the start index is included, the stop index is excluded, and the step controls how indices advance.

For text = "Python", text[2:4] returns "th"; the character at index 4 is outside the slice. text[::-1] returns a reversed copy. A slice of length (k) takes time and space proportional to the characters returned.

Useful string operations

text = "  Hello, World  "

text.strip()                  # remove surrounding whitespace
text.lower()                  # case conversion; returns a new string
text.replace("World", "Ada")  # replace substring
text.split(",")               # split into parts
", ".join(["red", "blue"])    # join parts into a string
"World" in text               # substring test
text.find("World")            # index, or -1 if absent

Use casefold() for caseless comparisons across languages. Use split() without an argument to split on runs of whitespace; split(" ") splits only on literal spaces and can leave empty strings.

Characters and bytes

Python strings contain Unicode code points; files and network protocols use bytes. Encode when writing bytes and decode when reading them:

raw = "café".encode("utf-8")  # five bytes
text = raw.decode("utf-8")    # four Unicode code points

Some visible characters use multiple code points, so a displayed symbol is not always one index. Specify an encoding when opening text files for consistent behavior. Unicode normalization can make canonically equivalent text comparable; choose a normalization form that suits the application, because compatibility normalization may change distinctions.

Common mistakes with Python String Lab

  • Expecting a method to mutate the string: assign its returned value if you need to keep the result.
  • Using inclusive slice endpoints: the stop position is excluded.
  • Confusing bytes with characters: encoded byte length can differ from len(text).
  • Building output with repeated concatenation in a loop: collect pieces and use "".join(parts) for large output.

Sources and next steps

Run it in Python

Strings are immutable, and nearly everything surprising about them follows from that one fact. The middle block times the loop that every beginner writes against the idiom that replaces it.

strings.pyPython 3
Output

How the code works

  1. s[0] = "A" -> TypeErrorImmutability is enforced, not advisory. It is also what lets strings be hashable, and therefore usable as dictionary keys — a mutable string could not be.
  2. acc.text += "x"Each += allocates a new string and copies everything so far, so building n characters costs O(n²). The table measures growth rather than one timing, because that is the part that does not depend on the machine.
  3. why an attribute, not a local variableCPython has a special case that can resize a string in place when the target is a plain local and nothing else refers to it, which makes the textbook example look fine on some builds and not others. Storing into an attribute takes that variable out of the measurement — and a rescue that depends on the interpreter build is not one to write code against.
  4. "".join(parts)One pass to compute the total length, one allocation, one copy. It is the idiomatic answer, it is the fast one, and it does not depend on an interpreter detail to stay fast.
  5. s[2:6]Slicing copies. On a large string in a loop that is a real cost, and it is why algorithms that scan text carry indices around instead of slicing as they go.
  6. word == word[::-1]Readable, and it allocates a full reversed copy. The two-pointer version uses O(1) memory — worth knowing which one you are writing.

Change one thing

  • Swap acc.text for a plain local variable out and re-run. Whether the quadratic disappears depends on the interpreter you are running — which is the argument for join in one line.
  • Check whether two words are anagrams with sorted(a) == sorted(b), then again with Counter. O(n log n) against O(n).
  • Try "café"[::-1] and len("café"). Python 3 strings are sequences of code points, so this behaves — and an emoji with a skin-tone modifier still will not.

Where this runs

Real CPython, compiled to WebAssembly and running on your own machine — nothing is uploaded. The first run takes a few seconds while the interpreter downloads; after that it is immediate. Need more room, or want to paste your own attempt? Use the Python compiler.

Predict, then reveal

About to run: switch Method to Slicing [:]. Before it does — what happens to the readout?

Committing to an answer first is the point — the reveal runs the experiment on the visualisation above and reads the real value back, so nothing here is scripted.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Building a string by += in a loop is O(n²) because each step:

  2. The program accumulates into an object attribute rather than a local variable. Why?

  3. Immutability is also what allows strings to be:

Cheat sheet

Python String Lab

Slice, index, join and format Python strings interactively, and see how immutability shapes what each operation does.

ALGORITHMS · vizlearn.in/dsa/strings_in_python.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.