2017-06-18 208 views
0

请参阅下面的代码和输出。第三个打印语句没有OUTPUT。在print(long_word [3:7])等位置改变的打印语句给出了输出(elin)。Jupyter Notebook,Python3打印功能:无输出,无错误

# [ ] print the first 4 letters of long_word 
# [ ] print the first 4 letters of long_word in reverse 
# [ ] print the last 4 letters of long_word in reverse 
# [ ] print the letters spanning indexes 3 to 6 of long_word in Reverse 
long_word = "timeline" 
print(long_word[:4]) 
print(long_word[3::-1]) 
print(long_word[3:7:-1]) 
print(long_word[-1:-5:-1]) 

输出

time 
emit 

enil 

是怎么回事?这个问题的情况也在下面的链接中提出。目前尚未解决。

回答

1

Python中的分片操作是[start:end:step],当step=-1时,它表示以相反的方向获取值。

因此,当使用print(long_word[3::-1])时,它实际上是从索引3到索引0,索引0由反向标志step=-1确定。但是在使用print(long_word[3:7:-1])时,它表示从索引3到索引7,这不是倒序,而是碰撞。

+0

正确,所以它应该是print(long_word [6:2:-1])这是有效的。人们会预期在上述碰撞情况中出现错误,不是吗? – Pankaj113

+0

我认为这不是一个错误,因为你可以使用'print(long_word [2:15])'或'print(long_word [3:1])'。这只是一个理性的范围。 – danche

0

如果你要打印最后四个字母反向试试下面的代码:

long_word = "Characteristics" 

print(long_word[14:10:-1])  

结果:scit

14是一个开始字符串索引
10是结束串指数
- 1用于逐个反转字符串