String Characters and Their Indices

Given a string, write a Python program to print each character of the string and its corresponding index in the string.

Example 1:

Input: "Hello" 

Output: H 0, e 1, l 2, l 3, o 4

Example 2:

Input: "Python" 

Output: P 0, y 1, t 2, h 3, o 4, n 5

You can use a for loop and the built-in enumerate function to iterate through the string.

def print_characters_and_indices(s):
    for i, char in enumerate(s):
        print(char, i)

print_characters_and_indices("Hello")

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!