Exercise 33

Write a Python program that takes a string as input and displays the characters of even index. Example: for the string s = "Python", the program returns "Pto".

Solution

s = input("Enter a string: ")
result = ""
for i in range(len(s)):
    if i % 2 == 0:
        result += s[i]
print(result)





How this program works:

  1. First, we use the built-in input function: to prompt the user to enter a string. We store the user's input in the variable s.
  2. We initialize an empty string result: that will hold the characters of even index.
  3. We use a for loop: to iterate over all indices i of the string s.
  4. Inside the loop: we use the modulo operator % to check if the index i is even. If i is even, then we append the character at that index to the result string using the += operator.
  5. After all indices have been processed: we print the result string, which contains the characters of even index.

Here's an example of how to use this program:

s = "Python"
result = ""
for i in range(len(s)):
    if i % 2 == 0:
        result += s[i]
print(result)
"""
This would output:

Pto
"""

As you can see, the program correctly displays the characters of even index in the string "Python".

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 33: extact a characters of even index”

Leave a Reply