Skip to content
PythonStrings and Textbeginner18 min read

String Indexing and Slicing

Master zero-based indexing, negative indexes, slice boundaries, step values, and string reversal through clear examples and practice.

In this lesson, you will learn

  • ✓Explain how Python assigns indexes to characters in a string.
  • ✓Access individual characters using positive and negative indexes.
  • ✓Extract substrings using start, stop, and step values.
  • ✓Predict the behavior of omitted boundaries, negative steps, and out-of-range slice boundaries.
  • ✓Distinguish IndexError from slicing that produces an empty or partial string.
  • ✓Trace string indexing and slicing expressions and verify their exact output.

1. Understanding string indexes

An index is a number that identifies a character's position in a string. Python uses zero-based indexing, which means the first character has index 0, the second has index 1, and the third has index 2.

For example, in the string 'Python', the character 'P' is at index 0, 'y' is at index 1, and 'n' is at index 5. A string with six characters therefore has valid positive indexes from 0 through 5.

You can access a character using string[index]. For example, word[0] returns 'P'. The expression returns a string containing one character, not a separate character type.

You can also count backward from the end of a string using negative indexes. The index -1 refers to the last character, -2 refers to the second-to-last character, and so on. For a non-empty string, word[-1] retrieves its final character.

The len() function returns the number of characters in a string. For a non-empty string, the last character can be accessed with word[len(word) - 1] or word[-1]. The negative-index form is usually shorter and easier to read.

Read characters using positive indexes

Read characters using positive indexes
python
word = 'Python'
print(word[0])
print(word[1])
print(word[5])
print(len(word))
Output
P y n 6

The string 'Python' contains six characters. word[0] retrieves the first character, 'P'. word[1] retrieves the second character, 'y'. word[5] retrieves the sixth and final character, 'n'. len(word) returns 6, but 6 is not a valid index for this string.

Note

Positive indexing starts at 0. Negative indexing starts at -1 from the right. The last positive index of a non-empty string is len(string) - 1.

2. Index errors and string immutability

A valid index must identify a character that exists in the string. For a string of length 6, word[6] and word[-7] are out of range. Accessing either character directly raises IndexError.

An empty string, written as '', has length 0 and contains no valid character indexes. Therefore, attempting to evaluate empty[0] or empty[-1] raises IndexError.

Slicing behaves differently from direct indexing when a boundary is out of range. A slice can safely use boundaries outside the string's valid index range; Python returns the available portion rather than raising IndexError just because a slice boundary is out of range.

Strings are immutable, meaning you cannot replace a character in an existing string by assigning to one of its indexes. An expression such as word[0] = 'J' raises TypeError. To change the text, create a new string instead.

An out-of-range index

An out-of-range index
python
word = 'Python'
print(word[6])
Output
IndexError: string index out of range

The string has length 6, so its valid positive indexes are 0 through 5. Index 6 is outside the string. Python raises IndexError instead of returning a character. The output shown is the essential error message; the complete traceback and exact wording may vary by Python version and execution environment.

Caution

Do not confuse an invalid index with an out-of-range slice boundary. Direct indexing requires an existing character; slicing can return a partial or empty string when its boundaries fall outside the string.

3. Slicing with start and stop

Slicing extracts a portion of a string. Its basic syntax is string[start:stop]. The start identifies the first character to include, while the stop identifies the boundary where extraction ends.

The start position is included, but the stop position is excluded. This is one of the most important Python slicing rules. For example, word[1:4] includes indexes 1, 2, and 3, but not index 4.

A slice does not include the character at the stop index. This makes the number of selected characters easy to calculate when the indexes are valid and start is less than or equal to stop: the slice length is stop - start.

If you omit start, Python starts from the beginning for a positive-step slice. If you omit stop, Python continues to the end. Therefore, word[:3] extracts the first three characters, and word[2:] extracts the characters from index 2 through the end.

If start and stop are equal, a normal positive-step slice is empty. If start is greater than stop with a positive step, the slice is also empty. An empty slice is represented by ''.

Slice boundaries may be negative. For example, word[-4:-1] selects characters beginning at the fourth character from the end and stops before the last character. The same start-inclusive, stop-exclusive rule still applies.

Extract a range of characters

Extract a range of characters
python
word = 'Python'
print(word[1:4])
print(word[0:2])
print(word[2:6])
Output
yth Py thon

word[1:4] includes indexes 1, 2, and 3, producing 'yth'. word[0:2] includes indexes 0 and 1, producing 'Py'. word[2:6] includes indexes 2 through 5. Index 6 is only the stop boundary, so the result is 'thon'.

Note

For ordinary positive-step slicing, remember: include start, exclude stop. The stop value is a boundary, not the index of the last character you want.

4. Slicing with a step

Python also supports a step value. The full slice syntax is string[start:stop:step]. The step determines how far the selected index moves between characters.

A step of 1 selects consecutive characters. A step of 2 selects every second character, while a step of 3 selects every third character. For example, word[::2] selects indexes 0, 2, and 4 from 'Python', producing 'Pto'.

A positive step moves from left to right. A negative step moves from right to left. The step cannot be zero; a slice with a step of zero raises ValueError.

When the step is negative, Python moves backward from the start toward the stop boundary. For example, word[::-1] reverses the string. If start and stop are omitted, Python uses the appropriate boundaries for the direction of the step.

The stop boundary is still excluded when the step is negative. For instance, word[4:1:-1] selects indexes 4, 3, and 2, but excludes index 1.

A negative step does not automatically reverse every slice. The selected start, stop, and step must describe a valid backward traversal. For example, word[1:4:-1] is empty because the positive-direction boundary arrangement does not select any characters while moving backward.

Skip characters using a positive step

Skip characters using a positive step
python
word = 'Python'
print(word[::2])
print(word[1::2])
print(word[0:6:3])
Output
Pto yhn Ph

word[::2] selects indexes 0, 2, and 4, giving 'Pto'. word[1::2] selects indexes 1, 3, and 5, giving 'yhn'. word[0:6:3] selects indexes 0 and 3, giving 'Ph'. Index 6 is excluded as the stop boundary.

Caution

A step of 0 is invalid. For example, word[::0] raises ValueError. Use a positive or negative nonzero integer as the step.

5. A complete dry run: predict every slice

To understand slicing, write down the character indexes first. Then identify the start, stop, and step, and list only the indexes that the slice visits.

For positive steps, move from left to right and stop before the stop boundary. For negative steps, move from right to left and stop before the stop boundary. This process helps explain why some slices contain characters while others are empty.

Trace multiple slices

Trace multiple slices
python
word = 'Python'
print(word[1:4])
print(word[-1])
print(word[::2])
print(word[::-1])
Output
yth n Pto nohtyP

The first print() selects indexes 1, 2, and 3, producing 'yth'. The second print() uses negative index -1 to retrieve 'n'. The third print() selects indexes 0, 2, and 4, producing 'Pto'. The fourth print() uses step -1 to select all characters from right to left, producing 'nohtyP'.

Note

For every slice, identify the direction of the step before listing indexes. This is especially important for negative-step slices.

6. Practical use and boundary cases

Indexing and slicing are useful for extracting prefixes and suffixes, selecting parts of identifiers, inspecting file extensions, and preparing text for further processing.

A slice whose boundaries extend beyond the string returns the available characters. For example, 'Python'[0:100] returns 'Python'; it does not raise IndexError.

A slice of an empty string returns an empty string. Expressions such as ''[:3], ''[::2], and ''[::-1] are valid and produce ''. Direct indexing of an empty string, however, raises IndexError.

If a slice selects no characters, Python returns an empty string rather than raising an error. For example, 'Python'[4:2] is empty with the default positive step.

Indexing and slicing do not modify the original string. If you need different text, assign a newly constructed string to a variable.

Python string indexing operates on Unicode code points, not necessarily user-perceived characters. Some displayed symbols, such as certain emoji or letters combined with accent marks, can consist of multiple code points. For beginner exercises using ordinary English text, each visible character usually corresponds to one index.

Slice beyond the string boundaries

Slice beyond the string boundaries
python
word = 'Python'
print(word[0:100])
print(word[20:30])
print(word[4:2])
Output
Python

word[0:100] returns all available characters because the stop boundary extends beyond the string. word[20:30] is empty because its start is beyond the end and the positive-step slice selects no characters. word[4:2] is empty because the start is greater than the stop for a positive step. The second and third print() calls each produce a blank line.

Caution

An empty result is not necessarily an error. An invalid direct index raises IndexError, while a slice that selects no characters normally returns ''. A zero slice step raises ValueError.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming the first character has index 1.

Why it happens: Python strings are zero-indexed, so the first character is at index 0.

Incorrect Approach
script.py
python
Assuming the first character has index 1.
Correct Solution
script.py
python
Python uses zero-based indexing. The first character is at index 0, the second at index 1, and so on.

Key takeaway: Python uses zero-based indexing. The first character is at index 0, the second at index 1, and so on.

#2 Including the stop index in a slice.

Why it happens: A slice includes its start boundary but excludes its stop boundary, so the character at the stop index is omitted.

Incorrect Approach
script.py
python
Including the stop index in a slice.
Correct Solution
script.py
python
The start is included and the stop is excluded. The slice word[1:4] selects indexes 1, 2, and 3.

Key takeaway: The start is included and the stop is excluded. The slice word[1:4] selects indexes 1, 2, and 3.

#3 Using len(string) as the last valid positive index.

Why it happens: For a non-empty string, the last valid positive index is len(string) - 1; len(string) itself is one past the end.

Incorrect Approach
script.py
python
Using len(string) as the last valid positive index.
Correct Solution
script.py
python
The last valid positive index of a non-empty string is len(string) - 1. len(string) is the number of characters and is outside the valid index range.

Key takeaway: The last valid positive index of a non-empty string is len(string) - 1. len(string) is the number of characters and is outside the valid index range.

#4 Confusing negative indexes with negative slice steps.

Why it happens: Negative indexes count positions from the end, while a negative step controls the direction in which a slice traverses the string.

Incorrect Approach
script.py
python
Confusing negative indexes with negative slice steps.
Correct Solution
script.py
python
A negative index identifies a position counted from the end. A negative step controls traversal direction, moving from right to left.

Key takeaway: A negative index identifies a position counted from the end. A negative step controls traversal direction, moving from right to left.

#5 Assuming every slice with a negative step reverses the string.

Why it happens: A negative step traverses backward from the specified boundaries; it reverses the entire string only when the boundaries describe the whole string.

Incorrect Approach
script.py
python
Assuming every slice with a negative step reverses the string.
Correct Solution
script.py
python
Only a slice such as string[::-1] selects the entire string backward. Other negative-step slices depend on their start and stop boundaries.

Key takeaway: Only a slice such as string[::-1] selects the entire string backward. Other negative-step slices depend on their start and stop boundaries.

#6 Expecting an out-of-range slice boundary to raise IndexError.

Why it happens: Slicing normally clips out-of-range boundaries instead of raising IndexError, unlike direct indexing.

Incorrect Approach
script.py
python
Expecting an out-of-range slice boundary to raise IndexError.
Correct Solution
script.py
python
Slices tolerate boundaries outside the string and return the available characters or an empty string. Direct indexing raises IndexError for an invalid position.

Key takeaway: Slices tolerate boundaries outside the string and return the available characters or an empty string. Direct indexing raises IndexError for an invalid position.

#7 Trying to assign to a string index.

Why it happens: Strings are immutable, so indexed assignment is not allowed; create a new string using slicing or another string operation.

Incorrect Approach
script.py
python
Trying to assign to a string index.
Correct Solution
script.py
python
Strings are immutable. Construct a new string with concatenation or slicing when you need modified text.

Key takeaway: Strings are immutable. Construct a new string with concatenation or slicing when you need modified text.

#8 Using a step of zero.

Why it happens: A slice step cannot be zero because Python cannot advance through the sequence with a zero stride.

Incorrect Approach
script.py
python
Using a step of zero.
Correct Solution
script.py
python
A slice step must be nonzero. A step of 0 raises ValueError.

Key takeaway: A slice step must be nonzero. A step of 0 raises ValueError.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is string indexing in Python?
Answer:
String indexing accesses a character at a particular position. Python uses zero-based indexing, so the first character is at index 0. Negative indexes count from the end, with -1 identifying the last character.
Q2:What is the difference between indexing and slicing?
Answer:
Indexing retrieves one character, such as word[0]. Slicing extracts a portion of a string, such as word[1:4]. Invalid direct indexes raise IndexError, while slice boundaries outside the string's range are generally handled by returning the available portion.
Q3:Why does word[1:4] return three characters rather than four?
Answer:
The start index is included, but the stop index is excluded. Therefore, word[1:4] selects indexes 1, 2, and 3, which is three characters.
Q4:How do you reverse a string without a loop?
Answer:
Use slicing with a negative step: word[::-1]. The omitted start and stop boundaries allow Python to traverse the entire string backward.
Q5:What is the difference between word[-1] and word[::-1]?
Answer:
word[-1] retrieves only the last character. word[::-1] creates a string containing all the original characters in reverse order.
Q6:What happens when a slice boundary is outside the string?
Answer:
Python adjusts slice boundaries to the available range instead of raising IndexError solely because a boundary is out of range. For example, 'Python'[0:100] returns 'Python'. Direct indexing at an invalid position does raise IndexError.
Q7:Can strings be modified using index assignment?
Answer:
No. Strings are immutable, so an assignment such as word[0] = 'J' raises TypeError. You can create a new string using concatenation or slicing and assign that new value to a variable.

Key takeaways

  • Python strings use zero-based indexing: the first character is at index 0.
  • Negative indexes count backward from the end, with -1 identifying the last character.
  • In a slice, the start is included and the stop is excluded.
  • The full slice syntax is string[start:stop:step].
  • Omitted slice boundaries allow you to start at the beginning or continue to the end, depending on the step direction.
  • A negative step moves backward, and string[::-1] reverses a string.
  • Out-of-range direct indexing raises IndexError, while out-of-range slice boundaries are generally allowed.
  • Strings are immutable; create a new string rather than assigning to an indexed character.
  • A zero slice step raises ValueError, and a slice that selects no characters returns an empty string.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: