Substrings

In Python, you can take part of a string by giving a start position and an end position.

The format is:

string[start:end]
  • start = the position where the substring begins (included).
  • end = the position where the substring stops (not included).
  • The first character is at position 0.

Examples

# Start with a word
word = "python"

# --- Simple substrings ---
# First 2 letters (positions 0 and 1)
print(word[0:2])   # "py"

# Middle part (positions 2, 3, 4)
print(word[2:5])   # "tho"

# Whole word (positions 0 to 5)
print(word[0:6])   # "python"
# Practical example: Working with dates stored as text
date = "2025-09-24"   # format: YYYY-MM-DD

# Get the year (first 4 characters, positions 0–3)
year = date[0:4]
print("Year:", year)   # "2025"

# Get the month (characters at positions 5–6)
month = date[5:7]
print("Month:", month) # "09"

# Get the day (characters at positions 8–9)
day = date[8:10]
print("Day:", day)     # "24"

Loops and substrings

Sometimes we don’t just want one substring — we want to look at every character in a string one by one.
We can do this with a for loop and the string[start:end] format.

  • The loop goes through each position in the string.
  • At each step, we use word[i:i+1] to take just one character.
  • This is useful if we want to check or print every letter separately.
# Example: print each character of a word using substrings
word = "python"

# Loop through all positions in the word
for i in range(len(word)):
    # Take the character from position i up to i+1
    print(word[i:i+1])

Arrays and substrings

You can use substrings on strings inside arrays.
The format is:

array[position][start:end]
  • array[position] picks one string from the array.
  • [start:end] then takes part of that string.
# Print the year from each string
dates = ["2025-09-24", "1999-12-31", "2001-06-12"]

for i in range(len(dates)):
    print(dates[i][0:4])    # first 4 characters of each string