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

  • Number Manipulation and F-Strings in Python, with examples:

    Python, mathematical operators are symbols that perform arithmetic operations on numerical values. Here’s a breakdown of the key operators: Basic Arithmetic Operators: Other Important Operators: Operator Precedence: Python follows the standard mathematical order of operations (often remembered by the acronym PEMDAS or BODMAS): Understanding these operators and their precedence is essential for performing calculations in…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • Vs code

    What is VS Code? 💻 Visual Studio Code (VS Code) is a free, lightweight, and powerful code editor developed by Microsoft. It supports multiple programming languages (Python, JavaScript, Java, etc.) with: VS Code is cross-platform (Windows, macOS, Linux) and widely used for web development, data science, and general programming. 🌐📊✍️ How to Install VS Code…

Leave a Reply

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