Chapter 14: String Indexing and Slicingยถ

๐Ÿš€ Open Notebookยถ

Open In Colab Open In Kaggle

๐Ÿ“บ Video Tutorialยถ

Watch on YouTube

String indexing in Python is easy โœ‚๏ธ (6:17)

๐Ÿ“š What Youโ€™ll Learnยถ

Access and extract parts of strings using indexing and slicing - essential for text processing!

๐ŸŽฏ Learning Objectivesยถ

  • Understand zero-based indexing

  • Use positive and negative indices

  • Slice strings with [start:end:step]

  • Reverse strings and extract substrings

๐Ÿ“– Concept Explanationยถ

Indexingยถ

Each character in a string has a position (index) starting from 0.

String: "PYTHON"
Index:   0 1 2 3 4 5
Negative:-6-5-4-3-2-1

Slicing Syntaxยถ

string[start:end:step]
  • start: Beginning index (inclusive)

  • end: Ending index (exclusive)

  • step: Interval between characters

๐Ÿ’ก Examplesยถ

Single Character Accessยถ

word = "Python"
print(word[0])   # P (first character)
print(word[3])   # h (fourth character)
print(word[-1])  # n (last character)
print(word[-2])  # o (second to last)

Slicing Rangesยถ

text = "Programming"
print(text[0:4])   # "Prog" (index 0 to 3)
print(text[3:7])   # "gram" (index 3 to 6)
print(text[:4])    # "Prog" (start to index 3)
print(text[4:])    # "ramming" (index 4 to end)
print(text[:])     # "Programming" (entire string)

Step Parameterยถ

numbers = "0123456789"
print(numbers[::2])   # "02468" (every 2nd char)
print(numbers[1::2])  # "13579" (every 2nd, starting at 1)
print(numbers[::3])   # "0369" (every 3rd char)

Reversing Stringsยถ

word = "Python"
print(word[::-1])  # "nohtyP" (reversed)

# Practical use: palindrome checker
word = "racecar"
if word == word[::-1]:
    print("It's a palindrome!")

โœ๏ธ Practice Exercisesยถ

  1. Extract first 3 characters from a string

  2. Get the last 4 characters

  3. Extract every other character

  4. Reverse a userโ€™s name

  5. Check if a string is a palindrome

  6. Extract domain from email (after @)

  7. Get file extension from filename

๐ŸŽฎ Real-World Examplesยถ

Credit Card Formatterยถ

card = "1234567812345678"
formatted = f"{card[0:4]}-{card[4:8]}-{card[8:12]}-{card[12:16]}"
print(formatted)  # 1234-5678-1234-5678

# Hide middle digits
hidden = f"{card[0:4]}-****-****-{card[-4:]}"
print(hidden)  # 1234-****-****-5678

Extract Informationยถ

date = "2024-01-15"
year = date[0:4]    # "2024"
month = date[5:7]   # "01"
day = date[8:10]    # "15"
print(f"Year: {year}, Month: {month}, Day: {day}")

URL Parserยถ

url = "https://www.example.com/page"
protocol = url[0:5]        # "https"
domain = url[12:23]        # "example.com"
path = url[23:]            # "/page"

๐Ÿ“ Common Patternsยถ

First/Last N Charactersยถ

text = "Hello World"
first_5 = text[:5]    # "Hello"
last_5 = text[-5:]    # "World"

Remove First/Last N Charactersยถ

text = "Hello World"
without_first = text[1:]   # "ello World"
without_last = text[:-1]   # "Hello Worl"

Every Nth Characterยถ

text = "ABCDEFGHIJ"
every_2nd = text[::2]  # "ACEGI"
every_3rd = text[::3]  # "ADGJ"

๐Ÿš€ Challenge Projectsยถ

  1. Social Security Number Formatter: XXX-XX-XXXX

  2. Phone Number Parser: Extract area code, prefix, line number

  3. Acronym Maker: Take first letter of each word

  4. Text Truncator: Limit text to N characters + โ€œโ€ฆโ€

  5. Caesar Cipher: Shift characters by N positions

๐Ÿ” Slicing Tricksยถ

Copy a Stringยถ

original = "Python"
copy = original[:]  # Creates a copy

Reverse Wordsยถ

sentence = "Hello World"
words = sentence.split()
reversed_words = [word[::-1] for word in words]
result = " ".join(reversed_words)
print(result)  # "olleH dlroW"

Extract Extensionยถ

filename = "document.pdf"
extension = filename[filename.rfind('.')+1:]
print(extension)  # "pdf"

๐ŸŽ“ Key Takeaways from Videoยถ

  1. Strings are text data enclosed in quotes

  2. Follow along with the video for hands-on practice

  3. Experiment with the code examples to deepen understanding

๐Ÿ’ก These points cover the main concepts from the video tutorial to help reinforce your learning.

๐Ÿ”— Next Chapterยถ

Continue to Chapter 15: Format Specifiers to learn advanced string formatting!