Python for AIPython for AI
Python Basics

Indexing and slicing

Grab characters and pieces of a string

A string is a sequence of characters in a fixed order. Because the order is fixed, you can ask Python for "the first character" or "characters 2 to 5". That's indexing and slicing.

Every character has a position

Each character has a number called its index. Python starts counting at 0, not 1.

0 / -6
P
1 / -5
Y
2 / -4
T
3 / -3
H
4 / -2
O
5 / -1
N
Positions of each character in "PYTHON". Negative indexes count from the end.

Indexing: one character

Put the index in square brackets after the string.

python
word = "PYTHON"

print(word[0])   # P  (first)
print(word[3])   # H
print(word[-1])  # N  (last)
print(word[-2])  # O  (second from the end)
Use -1 whenever you want the last item. You don't need to know how long the string is.

Slicing: a piece of the string

A slice uses a colon: text[start:stop]. It includes start but stops before stop.

python
word = "PYTHON"

print(word[0:2])   # PY
print(word[2:5])   # THO
print(word[:3])    # PYT   (from the beginning)
print(word[3:])    # HON   (to the end)
print(word[-3:])   # HON   (last three characters)

Adding a step

A third number sets the step size. A step of -1 walks backwards, which reverses the string.

python
word = "PYTHON"

print(word[::2])   # PTO  (every second character)
print(word[::-1])  # NOHTYP (reversed)

Real example: trimming long text

AI programs often show a short preview of a long answer or document. Slicing makes that a one-liner.

python
answer = "Python is a popular programming language used for AI, data science, and automation."

preview = answer[:30] + "..."
print(preview)
# Python is a popular programmi...

Strings can't be changed in place

You can read a character by index, but you can't replace it. Strings are immutable. Build a new string instead.

python
word = "cat"
# word[0] = "b"   # TypeError!

word = "b" + word[1:]
print(word)  # bat

Common mistakes

  • Forgetting that counting starts at 0, so word[1] is the second character.
  • Expecting the stop index to be included. word[0:3] gives three characters: 0, 1 and 2.
  • Using an index that's too big: "abc"[5] raises an IndexError. Slices never raise this error. "abc"[0:50] just returns "abc".

What's next?

The same indexing and slicing rules also work for lists. Next, you'll learn how to convert values between types, for example turning the text "42" into the number 42.