w3resource

Python: Print the index of the character in a string


Find character indices in string.

Write a Python program to print the index of a character in a string.

Python String Exercises: Print the index of the character in a string

Sample Solution:

Python Code:

# Define a string 'str1'.
str1 = "w3resource"

# Iterate through the characters of the string using enumeration.
# 'index' contains the position of the character, and 'char' contains the character itself.
for index, char in enumerate(str1):
    # Print the current character, its position, and a descriptive message.
    print("Current character", char, "position at", index)

Sample Output:

Current character w position at 0                                                                             
Current character 3 position at 1                                                                             
Current character r position at 2                                                                             
Current character e position at 3                                                                             
Current character s position at 4                                                                             
Current character o position at 5                                                                             
Current character u position at 6                                                                             
Current character r position at 7                                                                             
Current character c position at 8                                                                             
Current character e position at 9 

Flowchart:

Flowchart: Print the index of the character in a string

For more Practice: Solve these Related Problems:

  • Write a Python program to iterate over a string and print each character along with its index using enumerate().
  • Write a Python program to display each character's position in a string on separate lines.
  • Write a Python program to create a list of tuples where each tuple contains a character and its index in the string.
  • Write a Python program to implement a function that returns a dictionary mapping each character in a string to its first occurrence index.

Python Code Editor:

Previous: Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.
Next: Write a Python program to check if a string contains all letters of the alphabet.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.