Skip to course content
Free course

Python Foundations / Module 2 / Strings, Indexing, and Slicing

Module 2 lesson

Strings, Indexing, and Slicing

Unit ID: M02-U04 Estimated active time: 22-30 minutes

A string is an ordered sequence of characters

Create a string with single or double quotation marks:

course_code = "PYTHON-101"

The quotation marks mark the string in source code. They are not part of the text value.

Indexing starts at zero

Each character has a position. Python counts the first position as 0.

print(course_code[0])
print(course_code[1])

The outputs are P and Y.

Negative indexes count from the end:

print(course_code[-1])
print(course_code[-3])

The outputs are 1 and 1 for this value. Trace the positions carefully rather than guessing.

A slice extracts a range

print(course_code[0:6])

Output:

PYTHON

The start position is included. The stop position is excluded. The slice [0:6] contains positions 0 through 5.

You may omit an endpoint:

print(course_code[:6])
print(course_code[7:])

Outputs:

PYTHON
101

Strings are immutable

You cannot replace one character directly:

course_code[0] = "J"

This raises a TypeError. Strings are immutable: operations create new string values rather than changing the existing value in place.

Create a new value instead:

new_code = "J" + course_code[1:]
print(new_code)

Output:

JYTHON-101

The result is not a sensible course code, but it demonstrates the operation.

Length and boundaries

print(len(course_code))

The length is 10. Valid positive indexes run from 0 to 9.

Trying course_code[10] raises IndexError. A slice beyond the end is more forgiving:

print(course_code[:100])

It returns the available string.

Practice

Use:

label = "M02-U04-STRINGS"

Extract:

  • M02 using a slice;
  • U04 using a slice;
  • the final word STRINGS; and
  • the final character using a negative index.

Then print the length of the complete label.

Takeaway

Strings are ordered, zero-indexed, and immutable. Indexes select one character; slices extract a range without changing the original. Next, we will clean and format text for human-readable output.