Python From Beginner to Advanced

0% completed

Previous
Next
Looping Through Strings in Python

Looping through a string allows you to access each character one at a time. Since strings are sequences of characters, you can iterate over them using a for loop. This is useful for tasks like character analysis, pattern matching, and text processing.

Using a "for" Loop to Iterate Over a String

Python treats strings as iterables, meaning you can loop through them character by character.

Example 1: Looping Through a String

Python3
Python3

. . . .

Explanation

  1. The for loop iterates over each character in "Hello, world!".
  2. The character variable holds the value of the current character in each iteration.
  3. print(character, end=" ") prints each character on the same line with a space separator.
  4. The output will display:
    H e l l o ,   w o r l d !
    

Using a "while" Loop to Iterate Through a String

A while loop can also be used to iterate through a string using an index-based approach.

Example 2: Using a "while" Loop

Python3
Python3

. . . .

Explanation

  1. The loop runs while index < len(text).
  2. text[index] accesses the character at the current index.
  3. index += 1 moves to the next character.
  4. The output will display:
    P y t h o n
    

Looping through strings in Python allows accessing each character individually. The most common way is using a for loop, which iterates over characters directly. A while loop with indexing provides more control over iteration.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next