Exercise16

Write a Python program that prompts the user to enter a string and then displays all the characters in the string by two different methods.
Example for s = "Python", the program displays the characters:
P
y
t
h
o
n

Solution

First method:

s = input("Enter a string: ")
print("The characters in the string are:")
for char in s:
    print(char)

In this program:

  1. we use the input() function: to prompt the user to enter a string and store it in the variable s.
  2. Then we use a for loop: to iterate over each character in the string
  3. And we use the print() function: to print result.
  4. The print() function: is called once for each character in the string, so each character is displayed

If you run this program and enter "Python" as the input, the output will be:

Enter a string: Python
The characters in the string are:
P
y
t
h
o
n





Second method:

# Ask the user to enter a string
s = input("Enter a string: ")
print("The characters in the string are:")
for i in range(0, len(s)):
    print(s[i])

 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 16: python algorithm that displays all the characters in a given string”

Leave a Reply