2017-06-18 210 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用於逐個反轉字符串