Data Engineering Lab

String Indexing & Slicing — Ranges, Steps, and Safe Boundaries

Overview

A Python str is an immutable sequence. s[i] picks one element; s[start:stop:step] copies a substring into a new string. Indexing is 0-based; negative indices count from the end. Slices use a half-open interval: start is included, stop is excluded — the same rule as range(start, stop).

This shows up everywhere in data work: fixed-width timestamps in logs, file paths, IDs, protocol headers, and quick normalisation before regex. The Practice Lab String Indexing & Slicing trains five muscle-memory patterns: dual-direction indexing, half-open substring slices, reverse traversal, step slicing for alternating characters, and suffix-relative filename parsing.

Use the diagrams below for a visual index ruler, half-open intuition, Lab Q2 colouring, reverse, and step lanes — then open the practice map for Q1–Q5 code.

Enable JavaScript to explore the interactive diagram.

Map to Practice Lab questions

Lab QSkill
Q1word[0] / word[2] / word[-1] on "Python" → P, t, n
Q2"Data Engineering" → text[:4] = Data, text[5:] = Engineering
Q3"pipeline"[::-1] → enilepip
Q4"Python" → text[::2] = Pto, text[1::2] = yhn
Q5"report_2024.csv" → filename[:-4] = report_2024, filename[-8:-4] = 2024

Practice here: Practice Lab → String Indexing & Slicing.

Enable JavaScript to explore the interactive diagram.

Syntax reference

FormMeaning
s[i]One element; IndexError if i out of range
s[i:j]From i inclusive to j exclusive; clips if beyond bounds
s[:j]Start at 0
s[i:]Through the end
s[i:j:k]Step k (may be negative)
s[::-1]Reverse the whole string

Industry norms

PracticeWhy
Prefer slices for “maybe empty”s[5:10] never raises; s[9] does if short — parsers love slices.
Combine with split / regexFixed offsets are brittle when formats drift; slice the stable prefix, then parse the rest.
Unicode awarenessOne user-perceived character (grapheme) can be several code points; indexing is by Python str element (code point), not “glyph”. For names/emoji-heavy text, higher-level libraries exist.
ImmutabilityNever “patch” s[i]; build s[:i] + new + s[i+1:] or use replace.
PerformanceEach slice copies O(length of slice); avoid tight loops that re-slice huge strings — chunk or use io / parsers.
Logs & PIISlicing for display (e.g. last 4 of an ID) still needs policy — don’t leak full tokens in logs.

Key takeaways

  • s[i] is strict; s[i:j] is forgiving.
  • stop is exclusive — "hello"[1:4] is "ell", not "ello".
  • len(s) is not a valid index; last index is len(s) - 1.
  • [::2] / [1::2] split even/odd lanes — useful for sampling and encoding-style exercises (Q4).
  • Negative slice bounds such as [:-4] stay relative to a stable suffix instead of assuming a fixed prefix length (Q5).

Examples

Example 1 — Q1: positive and negative addresses

word = "Python"
print(word[0])
print(word[2])
print(word[-1])

Output:

P
t
n

Example 2 — Q2: prefix and remainder

text = "Data Engineering"
print(text[:4])
print(text[5:])

Output:

Data
Engineering

The space occupies index 4, so [:4] stops before it.


Example 3 — Q3: reverse

word = "pipeline"
print(word[::-1])

Output:

enilepip

Example 4 — Q4: even- and odd-index stride lanes

text = "Python"
print(text[::2])
print(text[1::2])

Output:

Pto
yhn

Both slices use step 2. Changing the start from the default 0 to 1 selects the complementary lane.


Example 5 — Q5: suffix-relative filename parsing

filename = "report_2024.csv"
print(filename[:-4])
print(filename[-8:-4])

Output:

report_2024
2024

The stop -4 excludes the dot and three-letter extension. Starting at -8 selects the four year characters immediately before it.


Example 6 — Industry: ISO date prefix from a log line

line = "2026-04-13T14:22:01Z INFO batch=42 ok"
day = line[:10]
print(day)

Output:

2026-04-13

For real pipelines, validate with datetime.fromisoformat (or strict regex) instead of assuming fixed width forever.


Mistakes

Mistake 1 — Treating stop as inclusive

❌ Expecting "hello"[1:3] to be "ell".

✅ It is "el" — index 3 is the first excluded position.


Mistake 2 — s[len(s)]

❌ IndexError — valid indices are 0 … len(s)-1.

✅ Last character: s[-1] or s[len(s)-1].


Mistake 3 — Assigning to s[i]

❌ TypeError — strings are immutable.

✅ s = s[:i] + ch + s[i+1:] or s.replace(...).


Mistake 4 — word[-1:0:-1] and missing a character

❌ Reversal slice that stops before index 0 can drop the first character.

✅ Prefer word[::-1] for full reverse.


Mistake 5 — Confusing [:2] with [::2]

❌ [:2] = first two characters; [::2] = stride 2 over the whole string.


Interview

Q1. s[5] vs s[5:6]?

s[5] raises if out of range. s[5:6] returns a (possibly empty) substring and never raises for bounds.


Q2. Negative indices?

s[-k] is s[len(s)-k] for positive k. s[-n:] is the last n characters when n ≤ len(s).


Q3. Time cost of slicing?

Python builds a new string of length proportional to the slice — O(j − i) (plus step logic). No zero-copy “view” for str.


Q4. Does slicing work on bytes?

Yes — bytes also supports slicing; it returns bytes. Rules are the same; content is raw octets, not decoded text.


Q5. User-visible “character” vs index?

Python str indices address Unicode code points in the string’s logical sequence; combining marks and emoji ZWJ sequences can span multiple code points — “one glyph” ≠ always one index.


Q6. SQL vs Python offsets?

Many SQL SUBSTRING functions use 1-based start positions; Python is 0-based. Off-by-one bugs are common when porting queries mentally.


Python vs PySpark

On the driver, Python s[a:b] is normal. In Spark SQL expressions, substring(column, pos, len) uses **1-based pos — mirror of SQL, not Python. Prefer F.substring(F.col("c"), 1, 10) (example) for column substrings; keep Python slicing for literals and small driver-side prep.

The comparison table is generated for this topic. Use Try Now for Python and PySpark practice.


Python vs SQL

SQL SUBSTRING / LEFT / RIGHT express similar ideas with 1-based conventions in standard SQL. Dialects differ (SUBSTR in SQLite/Oracle-style APIs). Always check whether LENGTH is characters or octets for your engine and charset.

The comparison table is generated for this topic. Use Try Now for Python and SQL practice.