Python自学记录 - 006

课程:
Microsoft: DEV274x
Introduction to Python: Fundamentals
课时:
Mod1_2-1.2_Intro_Python

习题:
Task 6
long_word = “timeline”
[ ] print the last 4 letters of long_word in reverse
[ ] print the letters spanning indexes 3 to 6 of long_word in Reverse

解答:
这几天的课程讲的都是list中关于index的问题,做到这题的时候感觉脑子就有点不清楚了,总结一下

string[x] 返回第x+1个字符,这里的x指的是序列index,为实际字符-1
string[-x] 返回倒序第x个字符
string[start,stop] 返回从start开始到stop前一位的的字符,这里都是index,且不包含stop这个index上的字符
string[:stop] 返回从头到index stop的字符,包括stop这个字符
string[start:] 返回从start这个index开始的字符直到尾部
string[:] 返回整个string
string[::2] 从第一个字符开始,每两个字符返回一个字符
string[1::3] 从第二个字符(1st)返回每第三个字符
string[: :-1] 返回打印string,其中[::-1]代表从后向前取值,每次步进值为1

题目的解答是这个:

long_word = "timeline"
print(long_word[-1:-5:-1])
print(long_word[-2:-6:-1])

但是我在想,反向打印变量最后4个letters,有没有正向选择的办法?我尝试了print(long_word[4:8:-1],但是print不出接结果来,不知道是哪里的问题…
待解决

你可能感兴趣的:(Pyhon学习笔记)