Python:如果符合字符限制,如何打破循环?

时间:2017-10-07 18:44:44

标签: python loops

我正在创建一个长度必须正好为140个字符的字符串。我必须使用带有break语句的循环,并从给定列表中获取字符串项。

最后,我设法达到了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)))

4 个答案:

答案 0 :(得分:1)

news_ticker = news_ticker[:140]
如果你想做的话,

会将字符串截断为140个字符。

答案 1 :(得分:1)

您的回答将news_ticker作为列表返回,但它必须是一个字符串。它允许您使用.append函数,但您可以简单地连接字符串,如下所示:

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

答案 2 :(得分: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)

答案 3 :(得分:0)

news_ticker = ""
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"]
for headline in headlines:
    previous=news_ticker
    news_ticker = news_ticker + headline + " "
    #print(len(news_ticker))
    if len(news_ticker) >= 140:
        break
print(len(previous))