python小问题求解

来源:百度知道 编辑:UC知道 时间:2024/07/02 12:30:58
str=open("hello.txt",'w')
str.write("hellocarl")
str=open("hello.txt","r")
i=str.read()
str.close()
x=0
print type(i)
while 1:
try:
x=x+1
print i[len(i)-x]
except:
print"OK"
break
这个程序我想反向输出“hellocarl”这个字符串
为什么输出结果是:
l
r
a
c
o
l
l
e
h
l
r
a
c
o
l
l
e
h
总是输出了2遍,怎么能只输出1遍啊?

因为字符串索引号为负也可以输出,你的循环当x=10时,len(i)-x为-1,此时i[-1]='l',一次类推i[-2]='r',...,i[-9]='h'
而索引号为-10 时,遇到异常才退出,所以会输出两遍

加一句判断就ok了,
x=x+1
print i[len(i)-x]
if x==len(i):
break