Strings in Python Indexing,Traversal
Strings in Python and Indexing
Strings in Python are sequences of characters enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). They are immutable sequences of Unicode code points used to represent text.
String Characteristics
- Immutable: Once created, strings cannot be modified
- Ordered: Characters maintain their position
- Indexable: Individual characters can be accessed via indices
Creating Strings
python
single_quoted = 'Hello' double_quoted = "World" triple_quoted = '''This is a multi-line string'''
String Indexing
Python uses zero-based indexing for strings, where:
- The first character has index 0
- The second character has index 1
- And so on…
Positive Indexing
python
text = "Python" # P y t h o n # 0 1 2 3 4 5 print(text[0]) # 'P' print(text[3]) # 'h'
Negative Indexing
Python also supports negative indices that count from the end:
- The last character has index -1
- The second last has index -2
- And so on…
python
text = "Python"
# P y t h o n
# -6 -5 -4 -3 -2 -1
print(text[-1]) # 'n'
print(text[-3]) # 'h'
String Length and Traversal in Python
1. Length of a String
You can find the length of a string using the built-in len() function:
python
text = "Hello, World!" length = len(text) print(length) # Output: 13
2. Traversing a String Without Using range()
Method 1: Using a for loop directly
python
text = "Python"
# Traversing using for loop
for char in text:
print(char)
# Output:
# P
# y
# t
# h
# o
# n
Method 2: Using while loop
python
text = "Python"
i = 0
while i < len(text):
print(text[i])
i += 1
# Output:
# P
# y
# t
# h
# o
# n
Method 1: Using range() with index
python
text = "Python"
for i in range(len(text)):
print(f"Character at index {i}: {text[i]}")
Comparison
- Without range(): Simpler and more Pythonic when you just need the characters
- With range(): Useful when you need both the index and the character, or when you need to modify the traversal pattern (like stepping through every second character)
Example: Traversing Backwards
python
text = "Python"
# Without range
for char in reversed(text):
print(char)
# With range
for i in range(len(text)-1, -1, -1):
print(text[i])
# Both output:
# n
# o
# h
# t
# y
# P