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 ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null Printed characters: H e l l o
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)):print(self.text[i], end=' ')for i in range(len(self.text)):
for i in range(len(self.text)):
my_string[2] return when my_string = 'hello'?text = 'abc'?for char in text iterates over each character directly.word = 'python'
result = ''
for i in range(len(word)):
if i % 2 == 0:
result += word[i]
print(result)text = 'data':for i in range(len(text)):
print(text(i))text(i) which is a function call, causing a TypeError.s = 'abracddabba', write code to create a new string containing only the characters at odd indices. What is the resulting string?Pass the test and this pattern moves unknown