Bird
Raised Fist0
DSA Pythonprogramming

String Traversal and Character Access in DSA Python

Choose your learning style10 modes available
Mental Model
A string is a sequence of characters you can look at one by one from start to end.
Analogy: Like reading a sentence letter by letter to understand or find a specific word.
"H" -> "e" -> "l" -> "l" -> "o" -> null
 ↑
Dry Run Walkthrough
Input: string: "Hello", print each character one by one
Goal: To visit and print each character in the string in order
Step 1: Start at the first character 'H'
"H" -> "e" -> "l" -> "l" -> "o" -> null
 ↑
Why: We begin reading from the first character
Step 2: Print 'H' and move to next character 'e'
"H" -> "e" -> "l" -> "l" -> "o" -> null
    ↑
Why: We print current character and move forward to continue traversal
Step 3: Print 'e' and move to next character 'l'
"H" -> "e" -> "l" -> "l" -> "o" -> null
       ↑
Why: Continue printing each character in order
Step 4: Print 'l' and move to next character 'l'
"H" -> "e" -> "l" -> "l" -> "o" -> null
          ↑
Why: Keep moving forward to print all characters
Step 5: Print 'l' and move to next character 'o'
"H" -> "e" -> "l" -> "l" -> "o" -> null
             ↑
Why: Almost at the end, print each character
Step 6: Print 'o' and reach end of string
"H" -> "e" -> "l" -> "l" -> "o" -> null
                ↑
Why: Last character printed, traversal complete
Result:
"H" -> "e" -> "l" -> "l" -> "o" -> null
Printed characters: H e l l o
Annotated Code
DSA Python
class StringTraversal:
    def __init__(self, text: str):
        self.text = text

    def traverse_and_print(self):
        for i in range(len(self.text)):
            print(self.text[i], end=' ')

if __name__ == '__main__':
    s = StringTraversal("Hello")
    s.traverse_and_print()
for i in range(len(self.text)):
loop through each index from 0 to length-1 to access characters in order
print(self.text[i], end=' ')
print character at current index without newline to show sequence
OutputSuccess
H e l l o
Complexity Analysis
Time: O(n) because we visit each character once where n is string length
Space: O(1) because no extra space is used besides loop variables
vs Alternative: Direct indexing is simpler and faster than converting string to list first
Edge Cases
empty string ""
loop does not run, nothing is printed
DSA Python
for i in range(len(self.text)):
string with one character "A"
prints single character 'A' correctly
DSA Python
for i in range(len(self.text)):
When to Use This Pattern
When you need to process or examine each character in a string one by one, use string traversal to access characters by their position.
Common Mistakes
Mistake: Trying to modify characters directly in the string (strings are immutable)
Fix: Use a new string or list to store changes instead of changing original string
Mistake: Using incorrect index range causing index out of range error
Fix: Always loop from 0 to len(string)-1 using range(len(string))
Summary
It visits each character in a string one by one in order.
Use it when you want to read or process every character in a string.
Remember strings are like a chain of characters you can access by position starting at zero.

Practice

(1/5)
1. What does the expression my_string[2] return when my_string = 'hello'?
easy
A. An error because index 2 is out of range
B. The first character 'h'
C. The third character 'l'
D. The last character 'o'

Solution

  1. Step 1: Understand string indexing

    Strings in Python start indexing at 0, so index 2 means the third character.
  2. Step 2: Identify the character at index 2

    In 'hello', index 0='h', index 1='e', index 2='l'.
  3. Final Answer:

    The third character 'l' -> Option C
  4. Quick Check:

    Index 2 of 'hello' is 'l' [OK]
Hint: Remember string indexing starts at zero [OK]
Common Mistakes:
  • Thinking indexing starts at 1
  • Confusing index 2 with last character
  • Assuming index 2 is out of range
2. Which of the following is the correct way to loop through each character in the string text = 'abc'?
easy
A. for char in text: print(char)
B. for char in text[1]: print(char)
C. for i in range(text): print(i)
D. for i in text.length: print(text[i])

Solution

  1. Step 1: Understand how to loop over a string

    Using for char in text iterates over each character directly.
  2. Step 2: Check each option

    for i in range(text): print(i) tries to use range on a string (invalid). for char in text[1]: print(char) uses text[1] which is a single character, not iterable. for i in text.length: print(text[i]) uses text.length which is invalid in Python.
  3. Final Answer:

    for char in text: print(char) -> Option A
  4. Quick Check:

    Loop over string directly with for-in [OK]
Hint: Use 'for char in string' to loop characters [OK]
Common Mistakes:
  • Using range() directly on string
  • Using incorrect string length property
  • Trying to loop over a single character
3. What is the output of the following code?
word = 'python'
result = ''
for i in range(len(word)):
    if i % 2 == 0:
        result += word[i]
print(result)
medium
A. pyo
B. pto
C. pyhn
D. pthn

Solution

  1. Step 1: Understand the loop and condition

    The loop runs from i=0 to i=5 (length 6). It adds characters at even indices (0,2,4).
  2. Step 2: Identify characters at even indices

    word[0]='p', word[2]='t', word[4]='o'. Concatenate: 'pto'.
  3. Final Answer:

    pto -> Option B
  4. Quick Check:

    Even indices form 'pto' [OK]
Hint: Pick characters at even indexes using modulo [OK]
Common Mistakes:
  • Including characters at odd indexes
  • Confusing index counting starting at 1
  • Adding characters incorrectly
4. Find the error in the following code that tries to print each character of text = 'data':
for i in range(len(text)):
    print(text(i))
medium
A. Using parentheses instead of square brackets for indexing
B. Missing colon after for loop
C. Using len() on string is invalid
D. Variable i is not defined

Solution

  1. Step 1: Identify the indexing syntax error

    In Python, to access a character by index, square brackets [] are used, not parentheses ().
  2. Step 2: Check the code line

    The code uses text(i) which is a function call, causing a TypeError.
  3. Final Answer:

    Using parentheses instead of square brackets for indexing -> Option A
  4. Quick Check:

    Use text[i] to access characters, not text(i) [OK]
Hint: Use square brackets [] for indexing strings [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Forgetting colon after for loop (not here)
  • Misunderstanding len() usage
5. Given the string s = 'abracddabba', write code to create a new string containing only the characters at odd indices. What is the resulting string?
hard
A. bacdbr
B. brcdr
C. aracaa
D. badab

Solution

  1. Step 1: Identify odd indices in the string

    Indices start at 0. Odd indices are 1,3,5,7,9.
  2. Step 2: Extract characters at odd indices

    Characters: s[1]='b', s[3]='a', s[5]='d', s[7]='a', s[9]='b'. Concatenate: 'b'+'a'+'d'+'a'+'b' = 'badab'.
  3. Final Answer:

    badab -> Option D
  4. Quick Check:

    Characters at odd positions form 'badab' [OK]
Hint: Pick characters where index % 2 == 1 [OK]
Common Mistakes:
  • Including even indices
  • Starting index count at 1 instead of 0
  • Mixing up characters order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard