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¶
- Copy the code above
- Save it as a
.pyfile (e.g.,string_indexing.py) - Run it with:
python string_indexing.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials