2017-10-07 68 views
0

我正在創建一個字符串,它必須完全是140個字符。我必須使用帶有break語句的循環,並且字符串項來自給定列表。Python:如果符合字符限制,如何打破循環?

最後,我設法達到了147個字符。有沒有辦法截斷字符串?

headlines = ["Local Bear Eaten by Man", 
      "Legislature Announces New Laws", 
      "Peasant Discovers Violence Inherent in System", 
      "Cat Rescues Fireman Stuck in Tree", 
      "Brave Knight Runs Away", 
      "Papperbok Review: Totally Triffic"] 

news_ticker = "" 

for headline in headlines: 
    if len(str(news_ticker)) >= 140: 
     break 
    else: 
     news_ticker = list(news_ticker) 
     news_ticker.append(headline) 

print(news_ticker) 
print(len(str(news_ticker))) 

回答

1
news_ticker = news_ticker[:140] 

將截斷字符串爲140個字符,如果這是你想要做什麼。

1

你的答案會返回news_ticker作爲列表,但它需要是一個字符串。它可以讓你使用.append功能,但你完全可以串連像這樣的字符串:

for headline in headlines: 
    news_ticker += headline + " " 
    if len(news_ticker) >= 140: 
     news_ticker = news_ticker[:140] 
     break 
0
headlines = ["Local Bear Eaten by Man", 
      "Legislature Announces New Laws", 
      "Peasant Discovers Violence Inherent in System", 
      "Cat Rescues Fireman Stuck in Tree", 
      "Brave Knight Runs Away", 
      "Papperbok Review: Totally Triffic"] 

news_ticker = "" 
for headline in headlines: 
    news_ticker += headline + " " 
    if len(news_ticker) >= 140: 
    news_ticker = news_ticker[:140] 
    break 


print(news_ticker)