Data Structures14 min read

Strings as Structures

Treat strings like sequences: indexing, slicing, iteration, and why immutability matters when you build text processing and parsing logic.

David Miller
December 16, 2025
2.7k109

A string is also a sequence data structure.

Key idea:

  • string is ordered
  • string is immutable
  • you can index and slice it like lists/tuples

Indexing and slicing

s = "Python"
print(s[0])    # P
print(s[-1])   # n
print(s[1:4])  # yth

Looping

for ch in "abc":
    print(ch)

Why immutability matters

You cannot modify a character directly:

s = "cat"
# s[0] = "b"  # error

Instead, you create a new string:

s = "b" + s[1:]
print(s)  # bat

Common beginner need: building strings efficiently

If you are joining many parts:

parts = ["Hello", "from", "Python"]
result = " ".join(parts)
print(result)

Graph: string immutability

flowchart LR
  A[Old string] --> B[Cannot change in place]
  B --> C[Create new string]

Remember

  • strings behave like sequences
  • immutable means safe but you must rebuild for changes
  • join() is best for combining many parts
#Python#Beginner#String