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:

  1. We use first the input() function: to prompts the user to input a string using .
  2. Then, it initializes an empty list a_positions: to store the positions of 'a' in the string.
  3. The for loop: iterates over the indices of the string using the range() function.
  4. For each index i: the program checks if the character at that index is 'a'.
  5. If it is: the index is appended to the a_positions list.
  6. If no 'a' characters: are found in the string, the program prints a message saying so.
  7. 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

One thought on “Solution Exercise 18: python algorithm to test whether a given string contains a given character”

Leave a Reply