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

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

Leave a Reply

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