I1 · Python Programming for AI

Strings, Indexing and Slicing

A string is an ordered sequence of characters. Each character has an index, its position, starting at 0. text[i] gets one character, negative indexes count from the end, and slicing, text[start:stop], gets a part of the string from start up to, but not including, stop.

10 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

How would you get the first letter of every name in a list?

A string is an ordered sequence of characters. Each character has an index, its position, starting at 0. text[i] gets one character, negative indexes count from the end, and slicing, text[start:stop], gets a part of the string from start up to, but not including, stop.

In simple words

Write PYTHON with a number under each letter: P is 0, Y is 1, up to N at 5. word[0] is P. word[-1] is the last letter, N. word[0:3] takes positions 0, 1 and 2: PYT. word[::-1] reads it backwards.

Why it matters

Text is everywhere in AI: names, messages, reviews, prompts. Cutting text into pieces is the first step of language processing, from extracting initials to splitting a sentence into words.

How it works

ExpressionResult for word = "PYTHON"
word[0]"P"
word[-1]"N"
word[1:4]"YTH"
word[:2]"PY"
word[3:]"HON"
word[::-1]"NOHTYP"
len(word)6

In code

Initials from a full name, a reversed word, and a palindrome check.

initials.py
name = "Ananya Rao"
first, last = name.split()
print("Initials:", first[0] + last[0])

word = "PYTHON"
print("First:", word[0], "Last:", word[-1])
print("Middle part:", word[1:4])
print("Backwards:", word[::-1])
print("Length:", len(word))

for candidate in ["level", "python", "madam"]:
    print(candidate, "is a palindrome:", candidate == candidate[::-1])

Output

Initials: AR
First: P Last: N
Middle part: YTH
Backwards: NOHTYP
Length: 6
level is a palindrome: True
python is a palindrome: False
madam is a palindrome: True

Try it yourself

Slice results

For text = "LEARNING", match each slice to its result.

  • text[0]
  • text[-1]
  • text[0:5]
  • text[5:]
  • len(text)

Common mistakes

  • Starting to count at 1. The first index is 0.
  • Expecting the stop index to be included. text[0:3] stops before position 3.
  • Trying to change a character in place.

Check yourself

Question 1

1. For s = "DATA", what is s[1]?

Question 2

2. For s = "DATA", what is s[-1]?

Question 3

3. What does s[::-1] do?

Summary

  • Strings are sequences; indexes start at 0, negatives count from the end.
  • Slicing [start:stop] excludes stop; [::-1] reverses.
  • Strings can't be changed in place; build new ones.

Finished reading?

Sources: W3Schools: Python Strings