Exercise 18
Write a Python program that asks the user to input a string, and then checks if the string contains the letter 'a'. If it does, the program returns a message indicating the position(s) of 'a' in the string. If it does, the program returns a message indicating the position(s) of 'a' in the string.
Solution
string = input("Enter a string: ") a_positions = [] for i in range(len(string)): if string[i] == 'a': a_positions.append(i) if len(a_positions) == 0: print("The string does not contain the letter 'a'.") else: for pos in a_positions: print(f"The letter 'a' is in position: {pos}")
In this program:
- We use first the input() function: to prompts the user to input a string using .
- Then, it initializes an empty list a_positions: to store the positions of 'a' in the string.
- The for loop: iterates over the indices of the string using the range() function.
- For each index i: the program checks if the character at that index is 'a'.
- If it is: the index is appended to the a_positions list.
- If no 'a' characters: are found in the string, the program prints a message saying so.
- Otherwise: the program loops through the a_positions list and prints a message for each position. The message uses an f-string to insert the position into the string.
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 18 || Solution […]