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:
- we use the input() function: to prompt the user to enter a string and store it in the variable s.
- Then we use a for loop: to iterate over each character in the string
- And we use the print() function: to print result.
- 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
[…] Exercise 16. || Solution […]