簡體   English   中英

Jupyter Notebook,Python3 打印功能:無輸出,無錯誤

[英]Jupyter Notebook, Python3 print function: No output, No error

請參閱下面的代碼和輸出。 第三個打印語句沒有 OUTPUT。 替代的打印語句(例如 print(long_word[3:7]))給出輸出 (elin)。

# [ ] 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

什么給? 這個問題的情況也在下面的鏈接中提出。 目前還沒有解決。

Python 中的切片操作是[start:end:step] ,當step=-1 ,表示取反方向的值。

因此,當使用print(long_word[3::-1]) ,實際上是從索引 3 到索引 0,這是由反向標志step=-1確定的。 但是當使用print(long_word[3:7:-1]) ,它表示從索引 3 到索引 7 這不是相反的順序,它是一個沖突。

如果要反向打印最后四個字母,請嘗試以下代碼:

long_word = "Characteristics" 

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

結果: scit

14 是起始字符串索引
10 是結束字符串索引
-1 用於將字符串一一反轉

long_word = "timeline"

print(long_word[0:4])

print(long_word[3::-1])

print(long_word[-1:3:-1])

print(long_word[-3:-7:-1])

這是我嘗試過的,我認為這是對您問題的回答。

正確的代碼是:

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

time
emit
enil
nile

請注意,在反轉時,您首先聲明想要的結束索引,然后是想要的開始索引 - 1 秒(除了 0 索引不要從中減去一),如下所示:

long_word(想要結束索引:想要開始索引 - 1:-1)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM