Skip to content

Python Unicode, UTF-8, and String Operations

Step 16 of 41

Python String Slicing, Indexing, and Comparison

Introduction

Python string slicing selects code points by position, while comparisons use lexicographic order. Those rules explain why s[::-1] reverses a string, why s[2:5] excludes index 5, and why "10" < "9" is true even though 10 is the larger number.

This lesson continues Strings in PCAP-31-03 (18% of the score, 8 of 40 items), covering objective 3.2 and preparing the methods in objective 3.3. You will trace indexes, negative steps, membership, and immutable string operations, then repair a product-code normalizer.

Learning objectives

After this lesson you can:

  1. Read and write positive and negative indexes and predict IndexError.
  2. Compute any slice s[start:stop:step], including omitted bounds, negative values and reversed slices.
  3. Explain why strings are immutable and build replacement strings correctly.
  4. Use iteration, in, not in, + and * on strings and predict the result.
  5. Predict the result of comparisons with ==, <, > and of sorted() on strings.
  6. Trace a small text-processing function with realistic edge cases.

Indexing

A string is an ordered sequence. Each position has an index that starts at 0 for the first character. Python also accepts negative indexes, which count from the end: -1 is the last character, -2 the one before it, and so on.

Python
code = "PX-2048"
print(code[0])      # P
print(code[1])      # X
print(code[3])      # 2
print(code[-1])     # 8
print(code[-4])     # 2
print(len(code))    # 7

Each index selects one code point, which may be only part of a displayed character. Review Unicode code points and UTF-8 bytes for the distinction. The following table shows both numbering systems for "PX-2048".

Character P X - 2 0 4 8
Index 0 1 2 3 4 5 6
Negative index -7 -6 -5 -4 -3 -2 -1

For a string of length n, valid indexes run from -n to n - 1. Any other index raises IndexError:

Python
code = "PX-2048"
print(code[7])      # IndexError: string index out of range
print(code[-8])     # IndexError: string index out of range
print(""[0])        # IndexError, an empty string has no valid index

Indexing a string always returns a string of length one, never a separate character type. Therefore type("abc"[0]) is str, and "abc"[0][0][0] still works and returns "a". Indexes accept integers or objects implementing __index__; strings and floats are invalid: code["1"] and code[1.0] both raise TypeError.

Worked example: last character of a possibly empty value

Problem. A function must return the last character of a code, or "?" when the code is empty. A colleague wrote return code[-1]. What happens for "", and how do you fix it?

Step 1: trace the failing case. The empty string has length 0. Valid indexes are from -0 to -1, which is an empty range, so ""[-1] raises IndexError.

Step 2: choose a fix. Test the length before indexing, or use a bounded slice and handle its empty result. A slice clips out-of-range bounds, but invalid argument types and a zero step still fail.

Python
def last_char(code):
    return code[-1] if code else "?"

print(last_char("PX-2048"))   # 8
print(last_char(""))          # ?

Solution. An empty string is falsy, so the conditional expression returns "?" before any indexing happens.

Why other fixes are worse. Using code[len(code) - 1] still fails on "", because the index becomes -1, which is invalid for an empty string. Wrapping the whole call in except Exception hides unrelated errors. The explicit test states the rule and keeps the behaviour visible.

Slicing

A slice selects a sequence of code points and returns a string value. It does not modify the original; do not assume it always allocates a distinct object. The general form is s[start:stop:step].

  • start is the index of the first character included (default 0 for a positive step).
  • stop is the index where the slice ends and is excluded.
  • step is the distance between selected characters (default 1).
Python
s = "abcdefgh"
print(s[2:5])     # cde
print(s[:3])      # abc
print(s[5:])      # fgh
print(s[:])       # abcdefgh
print(s[::2])     # aceg
print(s[1::2])    # bdfh
print(s[-3:])     # fgh
print(s[:-3])     # abcde
print(s[-5:-2])   # def

A useful mental picture is to imagine the indexes as cuts between characters. The slice s[2:5] keeps everything between cut 2 and cut 5, which is three characters. That subtraction works here because the step is 1 and both bounds are within the string and ordered.

Out-of-range bounds are clipped

Unlike indexing, slicing never raises IndexError. Bounds beyond the string are silently clipped:

Python
s = "abcdefgh"
print(s[3:100])    # defgh
print(s[-100:2])   # ab
print(s[10:20])    # (empty string)
print(s[5:2])      # (empty string, start is after stop with a positive step)
print(len(s[10:20]))  # 0

This behaviour makes slices safe for "first N characters" logic: text[:80] works for any text, short or long.

Negative steps

A negative step walks backwards. When the step is negative, the defaults change: start defaults to the last character and stop defaults to before the first character.

Python
s = "abcdefgh"
print(s[::-1])      # hgfedcba
print(s[::-2])      # hfdb
print(s[6:2:-1])    # gfed
print(s[2:6:-1])    # (empty string)
print(s[-1:-4:-1])  # hgf

For s[6:2:-1], the slice starts at index 6 (g), moves left and stops before index 2, so it returns g, f, e, d. For s[2:6:-1], the start is already to the left of the stop but the step moves left, so nothing is selected: the result is empty.

Expression Result Reason
s[1:6:2] bdf indexes 1, 3, 5
s[::-1] hgfedcba reversed copy
s[7:0:-1] hgfedcb stops before index 0, so a is missing
s[7::-1] hgfedcba omitted stop goes all the way to the start
s[0:0] empty start equals stop

A step of 0 raises ValueError: slice step cannot be zero.

Worked example: extracting parts of a product code

Problem. Product codes have the form "EU-2026-0042-B". Using only slices and len, extract the region (EU), the year (2026), the sequence (0042) and the suffix (B), then rebuild the code in the reverse order of its fields without separators. What is printed?

Python
code = "EU-2026-0042-B"
region = code[:2]
year = code[3:7]
seq = code[8:12]
suffix = code[-1]
print(region, year, seq, suffix)
print(suffix + seq + year + region)

Step 1: number the characters. E=0, U=1, -=2, 2=3, 0=4, 2=5, 6=6, -=7, 0=8, 0=9, 4=10, 2=11, -=12, B=13. The length is 14.

Step 2: apply each slice. code[:2] takes indexes 0 and 1, giving EU. code[3:7] takes indexes 3 to 6, giving 2026. code[8:12] takes 8 to 11, giving 0042. code[-1] is index 13, giving B.

Step 3: print. The first line prints EU 2026 0042 B. The second concatenates the four strings: B + 0042 + 2026 + EU.

Solution. The output is

Text
EU 2026 0042 B
B00422026EU

Why mistakes happen. Writing code[3:6] would give 202 because the stop index is excluded. Writing code[8:11] would give 004. The reliable rule is: the length of the slice equals stop - start, so a four-character field starting at 3 ends at 7.

Strings are immutable

A string cannot be modified after creation. Assigning to an index or deleting a character raises TypeError:

Python
s = "cat"
s[0] = "b"          # TypeError: 'str' object does not support item assignment
del s[0]            # TypeError: 'str' object doesn't support item deletion

To "change" a string you build a new one and rebind the name:

Python
s = "cat"
t = "b" + s[1:]
print(s, t)         # cat bat
s = s.upper()
print(s)            # CAT

String transformations leave the original value unchanged. Use the returned result; object identity is not the rule to rely on. Forgetting to use the result is a typical error:

Python
name = "ada"
name.upper()
print(name)         # ada, the result of upper() was discarded
name = name.upper()
print(name)         # ADA

Immutability has a consequence for performance: repeated concatenation in a long loop creates many temporary strings. Collecting the parts in a list and calling "".join(parts) is the preferred approach (covered in the next chapter). It also explains why strings can be dictionary keys and set members, since their value never changes.

To replace one character at a position, combine slices:

Python
word = "hello"
pos = 1
fixed = word[:pos] + "a" + word[pos + 1:]
print(fixed)        # hallo

Iteration, membership, concatenation and repetition

Iteration

A for loop over a string yields one character at a time. enumerate adds the index, and reversed walks backwards without creating a slice:

Python
for c in "A-1":
    print(c, end="|")     # A|-|1|
print()
for i, c in enumerate("xyz"):
    print(i, c)            # 0 x / 1 y / 2 z
print("".join(reversed("abc")))   # cba
print(list("abc"))                 # ['a', 'b', 'c']

Membership with in and not in

For strings, in tests whether a substring appears, not only a single character:

Python
print("ab" in "cabin")     # True
print("ba" in "cabin")     # False
print("" in "cabin")       # True, the empty string is a substring of every string
print("A" in "cabin")      # False, case matters
print("x" not in "cabin")  # True

An exam trap is "ab" in ["cabin"]: for a list the test compares whole elements, so the result is False. The type of the right-hand operand decides the meaning of in.

Concatenation and repetition

The + operator joins two strings and * repeats a string. Both need operands of the right type:

Python
print("ab" + "cd")        # abcd
print("ab" * 3)           # ababab
print(3 * "ab")           # ababab
print("ab" * 0)           # (empty string)
print("ab" * -2)          # (empty string)
print("n=" + 5)           # TypeError: can only concatenate str (not "int") to str
print("n=" + str(5))      # n=5
print("-" * 10)           # ----------

The operator + never converts numbers automatically. Comparing with other languages is a frequent source of errors on the exam, where "5" + "5" is "55" and "5" * 2 is also "55", while 5 + 5 is 10.

Comparing strings

Strings are compared with ==, !=, <, <=, > and >=. Equality requires the same characters in the same order. Ordering is lexicographic: Python compares the first characters by code point; if they differ, that decides the result; if they are equal, it moves to the next pair. If one string is a prefix of the other, the shorter string is smaller.

Python
print("apple" < "banana")     # True, 'a' < 'b'
print("apple" < "apricot")    # True, 'p' < 'r' at index 2
print("app" < "apple")        # True, prefix is smaller
print("Zebra" < "apple")      # True, 'Z' (90) < 'a' (97)
print("10" < "9")             # True, '1' (49) < '9' (57)
print("abc" == "ABC")         # False
print("" < "a")               # True

The comparison "10" < "9" surprises many learners. It compares the text, not the numbers. Convert first when you need numeric order: int("10") < int("9") is False.

For ASCII text, compare lowercased values with a.lower() == b.lower(). For international caseless matching, casefold() is more suitable. Case conversion is separate from Unicode normalization. Comparing a string with a number using == returns False, but < raises TypeError:

Python
print("5" == 5)      # False
print("5" < 5)       # TypeError: '<' not supported between instances of 'str' and 'int'

Sorting strings

sorted() accepts any iterable of strings and returns a new list. It uses the same code point ordering:

Python
words = ["pear", "Apple", "fig", "apple", "10", "9"]
print(sorted(words))
# ['10', '9', 'Apple', 'apple', 'fig', 'pear']
print(sorted(words, key=str.lower))
# ['10', '9', 'Apple', 'apple', 'fig', 'pear']
print(sorted("banana"))
# ['a', 'a', 'a', 'b', 'n', 'n']
print(sorted(words, reverse=True)[:2])
# ['pear', 'fig']

ASCII digits (48 to 57) sort before ASCII uppercase letters (65 to 90), then ASCII lowercase letters (97 to 122). This is not locale-aware alphabetical ordering. With key=str.lower, "Apple" and "apple" compare equal, and sorted is stable, so they keep their original relative order: "Apple" came first in the input. Sorting a string directly returns a list of characters, not a string; join it back with "".join(...) when needed.

The list.sort() method sorts a list in place and returns None, while sorted() returns a new list. Calling print(words.sort()) prints None.

Comparison of related tools

Need Tool Returns Raises on failure
one character at a position s[i] str of length 1 IndexError
part of the string s[a:b:c] str ValueError for step 0; TypeError for invalid bound types
substring test x in s bool TypeError if x is not a string
repeat s * n new str TypeError if n is not an integer
ordering sorted(items) new list TypeError for mixed types

Tracing drill

Trace each line before reading the explanation.

Python
s = "Python3"
print(s[1:4])
print(s[-2::-2])
print(s[::3])
print("th" in s, "TH" in s)
print(s[:2] + s[2:] == s)
print(max("abc", "abd", "ab"))
  1. s[1:4] takes indexes 1, 2 and 3: yth.
  2. s[-2::-2] starts at index -2, which is n (index 5), and moves left two positions at a time: indexes 5, 3, 1. The characters are n, h, y, so the result is nhy.
  3. s[::3] takes indexes 0, 3 and 6: P, h, 3, giving Ph3.
  4. "th" is in "Python3" (indexes 2 and 3) and "TH" is not, so the output is True False.
  5. Cutting at any index and joining the two parts rebuilds the original string, so the result is True.
  6. max compares lexicographically. "abd" is larger than "abc" because d > c, and "ab" is smaller than both because it is a prefix. The output is abd.

Mini case study: the product-code normaliser

A warehouse receives codes typed by hand. Valid codes have the form AB-1234, but staff sometimes enter lowercase letters, extra spaces or a missing dash. The team writes this function:

Python
def normalise(raw):
    text = raw.strip().upper()
    if "-" not in text:
        text = text[:2] + "-" + text[2:]
    return text[:7]

print(normalise("  px-2048 "))
print(normalise("px2048"))
print(normalise("px-204812"))
print(normalise("p"))

Task. Trace the four calls, identify the weakness and propose a fix.

Solution.

  1. For " px-2048 ", strip() removes the outer spaces and upper() gives PX-2048. The dash is present, so nothing is inserted, and text[:7] keeps all 7 characters. Output: PX-2048.
  2. For "px2048", the text becomes PX2048. There is no dash, so it builds PX + - + 2048, giving PX-2048. Output: PX-2048.
  3. For "px-204812", the text is PX-204812, which has 9 characters. The final slice cuts it to PX-2048. Output: PX-2048. This silently drops 12, so a typing mistake disappears without any warning.
  4. For "p", the text is P. There is no dash, so the result is "P"[:2] + "-" + "P"[2:], which is P + - + empty string, giving P-. The final slice keeps both characters. Output: P-.

The weakness is in cases 3 and 4: the function never validates the result, so silent truncation and malformed codes go through. A safer version rebuilds the code and checks its length and shape, raising a clear error:

Python
def normalise(raw):
    text = raw.strip()
    if not text.isascii():
        raise ValueError("code must use ASCII: " + raw)
    text = text.upper()
    if "-" not in text:
        text = text[:2] + "-" + text[2:]
    if (len(text) != 7 or text[2] != "-"
            or not text[:2].isalpha() or not text[3:].isdecimal()):
        raise ValueError("invalid code: " + raw)
    return text

The function rejects "px-204812", "p", "12-ABCD", and non-ASCII inputs. It allows surrounding whitespace and a missing dash, but rejects spaces inside the code. The ASCII guard happens before uppercasing so Unicode case expansion cannot turn a rejected input into an accepted one. See validating text with string predicates for the predicates used here.

Common pitfalls and exam tips

  • The stop index is excluded. For step 1 with ordered, non-negative bounds inside the string, length is stop - start; otherwise normalize the bounds before counting.
  • Slicing clips out-of-range bounds. It still fails for invalid bound types or a zero step.
  • With a negative step, the defaults reverse: s[::-1] starts at the end.
  • Strings cannot be changed in place. Use slices and concatenation to build a new value, then rebind.
  • A discarded result is a bug: s.upper() alone does nothing to s.
  • in on a string tests substrings, on a list it tests elements.
  • "10" < "9" is True; text is not numbers.
  • + does not convert types; use str() or an f-string.
  • ASCII digits sort before ASCII uppercase and lowercase letters. General Unicode ordering uses code points.
  • A prefix is smaller than the longer string.

Exam tip. For every slice, write the index of each character under the string first, then list the selected indexes. This takes a few seconds and removes almost all off-by-one mistakes, particularly with negative steps.

Key terms

  • Index: position of a character, starting at 0, or from -1 at the end.
  • Slice: new string selected by start:stop:step.
  • Immutable: cannot be modified after creation.
  • Concatenation: joining strings with +.
  • Repetition: repeating a string with *.
  • Lexicographic order: comparison character by character using code points.
  • Stable sort: equal items keep their original order.

Summary checklist

  • I can convert between positive and negative indexes.
  • I can compute slices with omitted bounds and negative steps.
  • I know that slices clip bounds and indexing raises IndexError.
  • I know that strings are immutable and how to build a modified copy.
  • I can predict in, +, * and the type errors they raise.
  • I can predict comparison results and sorted() output.
  • I can trace a small normalising function and spot silent truncation.

Official sources