LEARN PYTHON | String Indexing, Slicing And Methods

Lesson objective

Read characters using zero-based and negative indices, extract slices with excluded stops, and use string methods without confusing returned values with changes to the original.

Learn

03.1 | STRING INDEXING, SLICING AND METHODS

01 | TEXT HAS POSITIONS

A string contains an ordered sequence of characters. A character may be a letter, digit, space or punctuation mark. In "ROBOT", the first character is R and the last is T.

Python names positions using an index. Indices begin at zero, so R is at index 0, O at 1, B at 2, O at 3 and T at 4. Five characters means the final non-negative index is four, not five.

This differs from the one-based string positions often used in Cambridge pseudocode. Read the language’s actual convention rather than transferring a memorised position rule.

word = "ROBOT"
print(word[0])
print(word[2])
print(len(word))

EXPECTED OUTPUT

R
B
5

02 | ONE INDEX RETURNS ONE CHARACTER

Square brackets after the string select a position. word[2] returns the character B as a one-character string. Python does not have a separate built-in CHAR type for this result.

len(word) returns the number of characters counted by Python, including spaces. For an ordinary non-empty string, valid non-negative indices run from zero through len(word) - 1.

An empty string has length zero and no valid character index. An out-of-range access, such as word[5] for ROBOT, raises IndexError rather than returning an empty character.

03 | NEGATIVE INDICES COUNT FROM THE END

-1 identifies the last character, -2 the one before it, and so on. For ROBOT, word[-1] is T and word[-5] is R. An index of -6 is beyond this string.

Negative indices are useful when a length may change. text[-1] can find a final character without first calculating the final positive index, but it still requires non-empty text.

The index is a position, not the character’s numeric value. If the text is "204", text[1] is the string "0"; it is not the number one or integer zero.

word = "ROBOT"
print(word[-1])
print(word[-2])

EXPECTED OUTPUT

T
O

04 | A SLICE TAKES A SEQUENCE OF CHARACTERS

A slice uses text[start:stop]. It includes start and excludes stop. word[1:4] takes indices one, two and three, giving OBO.

The second slice number is an excluded endpoint, not a character count. To take three characters from index one, use stop four. This differs from a start-and-length substring routine.

A slice produces a new string. It does not remove characters from the original. An out-of-range slice endpoint is clipped to the available sequence rather than producing the same IndexError as a single invalid index.

word = "ROBOT"
print(word[1:4])
print(word[2:99])
print(word)

EXPECTED OUTPUT

OBO
BOT
ROBOT

05 | OMITTED ENDS AND STEPS

word[:3] takes the beginning through index two. word[2:] takes index two onwards. word[:] copies the whole sequence’s value. With a positive step, a slice whose stop does not follow start can be empty.

A third part supplies a step: word[::2] takes every second character, giving RBT. word[::-1] reverses the sequence. The omitted endpoints adapt to a negative step; word[0:5:-1] is not a useful reversal because its direction conflicts with those bounds.

A zero slice step raises ValueError. Begin with simple slices, then predict stepped ones using the positions rather than guessing.

word = "ROBOT"
print(word[:3])
print(word[2:])
print(word[::2])
print(word[::-1])

EXPECTED OUTPUT

ROB
BOT
RBT
TOBOR

06 | STRINGS ARE IMMUTABLE

Immutable means the string object’s character contents cannot be changed in place. Assigning word[0] = "B" raises TypeError. You can instead create another string and assign that result to word.

Reassigning a variable is different from modifying the object it previously named. word = "B" + word[1:] creates a new value and associates the name with it. It does not rewrite the earlier string object.

This distinction explains why many string methods return a new value. Use or store that returned value when you want the transformed text.

word = "ROBOT"
new_word = "B" + word[1:]
print(new_word)
print(word)

EXPECTED OUTPUT

BOBOT
ROBOT

07 | CLEAN AND CHANGE CASE WITH METHODS

A method is an operation associated with a value or object. The dot connects a string to its method: text.strip() returns text without surrounding whitespace. lower() and upper() return case-converted strings.

Methods do not all have the same purpose. strip removes surrounding whitespace by default, not every internal space. lower changes letter case, not spelling or punctuation.

For simple English command responses, input(...).strip().lower() is useful normalisation: return cleaned text, then return its lowercase version. Normalising does not prove the response is one of the accepted choices.

response = "  YES  "
clean = response.strip().lower()
print(clean)
print(repr(response))

EXPECTED OUTPUT

yes
'  YES  '

08 | SEARCH, REPLACE AND COUNT

text.find("bot") returns the first matching start index, or -1 when absent. A returned -1 is a not-found marker here, not permission to index the last character accidentally.

replace(old, new) returns text with replacements; count(piece) counts non-overlapping occurrences. Use in when you only need to know whether a piece occurs. These text checks are case-sensitive unless you deliberately normalise.

A replacement does not alter the original string in place. Keep the return value, and test both a match and no match.

text = "robot robot"
print(text.find("bot"))
print(text.find("cat"))
print(text.count("robot"))
print(text.replace("robot", "drone"))

EXPECTED OUTPUT

2
-1
2
drone drone

09 | SPLIT TEXT AND JOIN PIECES

split() divides text into a list of pieces. With no separator argument, it splits on whitespace and handles runs of spaces. A list is an ordered collection, explored fully next.

join() builds a string from an iterable of string pieces, using the string before .join as the separator. "-".join(parts) places a hyphen between the pieces, not after every final piece.

Explicit separators behave differently: "a,,b".split(",") keeps an empty middle piece. Choosing a separator is part of deciding the data format.

parts = "robot   coding club".split()
print(parts)
print("-".join(parts))

EXPECTED OUTPUT

['robot', 'coding', 'club']
robot-coding-club

10 | EXPLORE POSITIONS AND SLICES

The demo uses ordinary letters, digits, spaces and punctuation. Change the text and choose one index or a start/stop slice. The displayed numbered cells make zero-based positions visible. This is a constrained teaching model, not a general Python runner.

Python strings handle Unicode too, but a visible symbol can contain more than one code point. The ASCII restriction keeps this activity focused on the basic indexing rule.

11 | TRACE THE RETURNED VALUE

For name = " Maya ", calling name.strip() without using its result leaves name referring to the original text. name = name.strip() stores the returned cleaned version.

Use repr(value) when you want a diagnostic representation that makes surrounding quotes and some escapes visible. Ordinary print can make spaces difficult to notice.

Challenge: create a display name cleaner, take its first three characters and report whether it contains a chosen letter. Test empty text, short text and surrounding spaces. Check before indexing an empty result.

PUT YOUR SKILLS TO WORK

Use the Section 3 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.

Section 3 challenges Python course navigation

MATCH THE PYTHON TERM TO ITS MEANING

Terminology

Terminology

String

An ordered immutable text sequence.

Index

An integer position in a sequence.

Zero-based

The first non-negative index is zero.

Negative index

A position counted from the end, starting at -1.

len()

Returns the length of a collection or sequence.

IndexError

A single sequence index is out of range.

Slice

A subsequence selected with start:stop:step.

Excluded stop

The endpoint is not included in a slice.

Slice step

The spacing and direction of selected positions.

Immutable

The object cannot be modified in place.

Rebinding

Associating a name with another object or value.

String method

An operation accessed through the text object.

strip()

Returns text without surrounding whitespace by default.

lower()

Returns lowercase text.

find()

Returns a match index or -1.

replace()

Returns text with specified substitutions.

split()

Returns a list of text pieces.

join()

Combines string pieces using a separator.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. For ROBOT, which are correct?
2. Which describe negative indexing?
3. Which describe word[1:4]?
4. Which are correct for ROBOT?
5. Which describe immutability?
6. Which describe strip?
7. Which describe find?
8. Which describe split and join?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain zero-based positions in ROBOT.

2. Compare indexing with slicing.

3. Calculate ROBOT[1:4] in words.

4. Explain string immutability versus variable reassignment.

5. Explain why an unused strip result does not clean the name.

6. Explain find returning -1.

7. Describe split followed by join.

8. Suggest tests for a first-character report.

CODE IT | YOUR INDEPENDENT CHALLENGE

Build a name cleaner and extract a safe substring. Explain indexing versus slicing.

Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for String Indexing, Slicing And Methods is coming soon. Complete the matching task and written questions in your exercise book.