In this program, we will take input from keyboard and display characters of a string in revers order
Asking user to enter some string
str = input('Enter any string: ')
Finding length of a string and displaying it
l = len(str)
print('Number of Characters:',l)
Creating a variable i and assigning -1 value to it
i = -1
Using while loop to display characters of a string in reverse order
while i >= -l:
print(str[i])
i-=1
In the first loop the value of i is -1 which display last character of a string. Inside loop a statement i-=1(-1-1) will make value of i to -2 which displays second last character and so on.
Ouput
Enter any string: Python
Number of Characters: 6
n
o
h
t
y
P
Complete Code
str = input('Enter any string: ')
l = len(str)
print('Number of Characters:',l)
i = -1
while i >= -l:
print(str[i])
i-=1
Code : Displaying characters in reverse order using negative index
Asking user to input any string from keyboard
str = input('Enter any string : ')
Finding length and displaying it
l = len(str)
print('Number of Characters: ',l)
Creating a variable i with value 1
i = 1
Using while loop to display characters in reverse order. In while loop, using negative index in print statement
while i <= l:
print(str[-i])
i+=1
Output
Enter any string : Python
Number of Characters: 6
n
o
h
t
y
P
Complete Code
str = input('Enter any string : ')
l = len(str)
print('Number of Characters: ',l)
i = 1
while i <= l:
print(str[-i])
i+=1