简体   繁体   中英

Using while: reverse printing

Doing python exercises already I've a problem with string:

#!/usr/bin/python

str = 'mandarino'
indice = len(str)-1
#print ("indice is:",indice)

while indice > 0:
        lett = str[indice]
        print (lett)
        indice = indice -1

Putting off "-1" the results is:

IndexError: string index out of range
while indice > 0:

should be

while indice >= 0:

to print the first character (index 0 ) at last.


BTW, if you use reversed , you don't need to calculate index yourself:

s = 'mandarino'
for ch in reversed(s):
    print(ch)

Side note: Don't use str as a varaible name. It will shadow a built in function/type str .

You can add:

indice = indice - 1

and change:

while indice > 0:

to

while indice >= 0:

so the script will be:

#!/usr/bin/python

str = 'mandarino'
indice = len(str)
indice = indice - 1
#print ("indice is:",indice)

while indice >= 0:

        lett = str[indice]
        print (lett)
        indice = indice -1

Better and handy:

indice = len(str)-1

Though above answers are correct..this is more pythonic way...

string = 'mandarino'
indice = len(string)

while indice >= 0:
    indice -= 1
    print (string[indice]),

You can also treat strings as list of characters and using reverse indexing, this way:

>>> str1 = 'mandarino'
>>> for ch in str1[::-1]:
    print ch


o
n
i
r
a
d
n
a
m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM