Skip to content

Basic String Operations and Indexing

CS 5001/5002 - Strings, Sequences & Sets

Code

#!/usr/bin/env python3
"""
Basic String Operations and Indexing
CS 5001/5002 - Strings, Sequences & Sets

This file demonstrates fundamental string operations including:
- String creation and basic properties
- Zero-based indexing
- Negative indexing
- String length calculation
"""

# String creation and basic properties
name = "northeastern"
city = "boston"

# Strings are sequences - we can access individual elements
print(f"First character of {name}: {name[0]}")  # 'n'
print(f"Last character of {city}: {city[-1]}")   # 'n'
print(f"Length of {name}: {len(name)}")          # 12

# String indexing follows zero-based numbering
word = "python"
print("Index positions in 'python':")
for i in range(len(word)):
    print(f"Index {i}: '{word[i]}'")

# Negative indexing counts from the end
print(f"word[-1] = '{word[-1]}'")  # 'n'
print(f"word[-2] = '{word[-2]}'")  # 'o'

How to Use

  1. Copy the code above
  2. Save it as a .py file (e.g., string_indexing.py)
  3. Run it with: python string_indexing.py

Part of CS 5001/5002 - Strings, Sequences & Sets materials