2016-08-25 54 views
-1

需要創建一個程序,每行打印一個單詞,但僅當該單詞少於4個字符時纔打印。我有這個迄今爲止每行打印一個單詞的程序

的投入將是一個列表,如[「不」,「非常」,「好」,「在」,「巨蟒」]

string = input("Enter word list:") 

txt = string.split() 

for words in txt: 

    print(words) 

當輸入是列表中,它打印在這一條線,但如果輸入是文本,例如

輸入單詞列表:不是很擅長蟒蛇

那麼它會打印上自己的一條線的每一個字。

不知道如何實現一個4字符只有印刷和不知道如何獲取列表打印它的元素在它自己的線路

回答

1

,則檢查字的長度。

string = input('Enter word list:\n') 
txt = string.split() 

for word in txt: 
    if len(word) < 4: 
     print('{0}'.format(word)) 
    else: 
     continue 
+1

你可以只做'print(word)'而你不需要'else' :) – Karin

+0

是真的,只是想明確 – n1c9

0

使用內置函數len()來計算每個單詞的長度。我還包括一個簡單的解析if語句來檢測您的輸入是否是一個列表。

string = raw_input('Enter word list: ') 

if string[0] == "[" and string[-1] == "]": # simple method to parse 
    print(string) 
else: 
    txt = string.split() 

    for words in txt: 
     if len(words) <= 4: 
      print(words) 
+0

當輸入是停止桌面而不是當輸入是列表時例如['stop','desktop'] – jason00

+0

@ jason00因此,如果輸入是'['stop','desktop']',則需要打印整行,即輸出爲'['stop','desktop' ]'以及?你能否爲你的問題添加更多細節? –

+0

輸入是['stop','desktop','here'] outt put應停止在第一行,並且在那裏沒有括號或引號的行上 – jason00

0

當您輸入['Not','very','good','at','python']時,會出現','。但是當你輸入「不太擅長python」時,沒有','。

0

是你提供的字面輸入['不','非常','好','at','python']?
如果這是你的問題。輸入被視爲文字字符串,而不是列表。在該輸入上調用拆分將生成輸入「列表」的單個項目列表,因爲該字符串中沒有空白分隔。 我也沒有看到任何代碼確定打印的字長,但也許這只是省略。

+0

我想添加一些確定字長的東西,不知道如何實現它 – jason00

+0

因此,你只是想做 如果len(words)<4: print(words) – Chris