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

  1. Immutable: Once created, strings cannot be modified
  2. Ordered: Characters maintain their position
  3. 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

Similar Posts

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  •  Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? 🦆 The name comes from the saying: “If it walks like a duck and it quacks like…

  • Dot (.) ,Caret (^),Dollar Sign ($), Asterisk (*) ,Plus Sign (+) Metacharacters

    The Dot (.) Metacharacter in Simple Terms Think of the dot . as a wildcard that can stand in for any single character. It’s like a placeholder that matches whatever character is in that position. What the Dot Does: Example 1: Finding Words with a Pattern python import re # Let’s find all 3-letter words that end with “at” text…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

Leave a Reply

Your email address will not be published. Required fields are marked *