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 · Sublevel Beginner 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.

Overview

  • A string is an ordered, immutable sequence of characters.
  • Each character has a position (index) starting at 0; len(s) gives the number of characters.
  • Negative indexes count from the end: s[-1] is the last character.
  • Slicing s[start:stop:step] copies a part; stop is not included.
  • Because strings are immutable, s[0] = "X" fails; build a new string instead.
  • Indexing past the end raises IndexError, but slicing past the end safely returns what exists.

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.

Key terms

String
An ordered, unchangeable sequence of characters.
Index
A character's position, counted from 0 at the left or from -1 at the right.
Slice
A part of a sequence taken with [start:stop:step].
len()
Returns the number of characters in a string.
Immutable
Cannot be changed in place; you create a new string instead.
Escape sequence
A backslash code for a special character, such as \n for a new line.

Types

Two families of types matter here: the kinds of string literal you can write, and the kinds of access you can use to reach characters.

1. Quoted strings: single and double quotes

Text written inside ' ' or " ", which mean exactly the same in Python.

  • How it works: Choose the quote that is not inside the text, or escape it with a backslash; escape sequences such as \n (new line) and \t (tab) add special characters.
  • Example: "It's raining" or 'She said "hello"'.
  • When to use it: Use them for ordinary one-line text.

2. Triple-quoted and raw strings

Strings in """ """ that can span several lines, and r"..." strings that treat backslashes literally.

  • How it works: Triple quotes keep line breaks exactly as typed; a raw string turns off escape sequences.
  • Example: A multi-line address in triple quotes; r"C:\new\data" keeps \n as two characters.
  • When to use it: Use triple quotes for long messages and docstrings; use raw strings for Windows paths and regular expressions.

3. Positive indexing

Reaching one character by its position counted from the start, beginning at 0.

  • How it works: s[i] returns the character at index i; valid indexes run from 0 to len(s) - 1.
  • Example: In s = "PYTHON", s[0] is "P" and s[3] is "H".
  • When to use it: Use it to read characters at known positions, such as the first letter of a name.

4. Negative indexing

Reaching a character by counting back from the end, with -1 as the last character.

  • How it works: Python converts s[-k] to s[len(s) - k], so you never need to compute the length yourself.
  • Example: In "PYTHON", s[-1] is "N" and s[-3] is "H".
  • When to use it: Use it to read endings, such as file extensions or the last digit of a roll number.

5. Basic slicing

Copying a range of characters with s[start:stop].

  • How it works: It includes start and stops just before stop; leaving out start means from the beginning, leaving out stop means to the end.
  • Example: "PYTHON"[0:2] is "PY"; "PYTHON"[2:] is "THON"; "2024-08-15"[:4] is "2024".
  • When to use it: Use it to cut out fixed parts of codes, dates and IDs.

6. Slicing with a step

Taking every k-th character with s[start:stop:step], including backwards with a negative step.

  • How it works: The step says how far to jump; s[::2] takes every second character and s[::-1] walks backwards, reversing the string.
  • Example: "PYTHON"[::2] is "PTO"; "madam"[::-1] is "madam", so it is a palindrome.
  • When to use it: Use it to reverse text, check palindromes or sample characters at regular intervals.

Explained in detail

Counting from zero

Python, like most programming languages, numbers positions from 0. In word = "PYTHON", word[0] is "P" and word[5] is "N". There is no word[6]: asking for it raises IndexError: string index out of range. Negative indexes count from the end, so word[-1] is "N" and word[-2] is "O", which is handy when you want the last character without knowing the length. Counting from zero feels odd at first, but it makes slicing arithmetic neat: the slice word[a:b] always contains exactly b - a characters.

Slicing in full

SliceResult for "PYTHON"Meaning
word[0:2]"PY"From 0 up to, not including, 2
word[:3]"PYT"Missing start means the beginning
word[3:]"HON"Missing stop means the end
word[-3:]"HON"The last three characters
word[::2]"PTO"Every second character
word[::-1]"NOHTYP"Reversed
word[2:100]"THON"Slices never raise errors for out-of-range limits

Strings cannot be changed in place

Strings are immutable. word[0] = "J" raises TypeError. To change a string you build a new one, for example "J" + word[1:] gives "JYTHON". This sounds limiting, but it makes strings safe to share: if two variables refer to the same string, neither can change it under the other's feet. It also lets Python use strings as dictionary keys, which you will rely on constantly.

Text in many languages

Python 3 strings are Unicode, so they can hold Hindi, Tamil, Urdu, emoji and every major script. One subtlety matters for Indian languages: what you see as one letter may be several Unicode code points. "नमस्ते" looks like four units on screen, but len("नमस्ते") is 6, because vowel signs and the halant are separate code points. Slicing such text by index can split a letter from its vowel sign. For serious text processing, which you will meet in the NLP module, libraries treat these combined units, called grapheme clusters, properly.

  • Use "in" to test for a substring: "TH" in word is True.
  • Use \n for a new line and \t for a tab inside a string.
  • Put r before a string to keep backslashes as they are, useful for Windows paths.

Slicing is not only for strings. Exactly the same rules work on lists and tuples, and later on NumPy arrays and pandas columns, so time spent mastering it here pays off across the whole course.

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