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:
- 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.
- We initialize an empty string result: that will hold the characters of even index.
- We use a for loop: to iterate over all indices i of the string s.
- 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.
- 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
[…] Exercise 33 || Solution […]