进行python练习我遇到了字符串问题:
#!/usr/bin/python
str = 'mandarino'
indice = len(str)-1
#print ("indice is:",indice)
while indice > 0:
lett = str[indice]
print (lett)
indice = indice -1
结果是“-1”结果是:
IndexError: string index out of range
答案 0 :(得分:1)
虽然以上答案是正确的......这更多pythonic
方式......
string = 'mandarino'
indice = len(string)
while indice >= 0:
indice -= 1
print (string[indice]),
答案 1 :(得分:1)
您还可以将字符串视为字符列表并使用反向索引,这样:
>>> str1 = 'mandarino'
>>> for ch in str1[::-1]:
print ch
o
n
i
r
a
d
n
a
m