Python:如果满足字符限制,如何打破循环?
我正在创建一个长度必须正好为140个字符的字符串。我必须使用带break语句的循环,字符串项取自给定的列表 最后,我设法达到了147个字符。有没有办法截断字符串Python:如果满足字符限制,如何打破循环?,python,loops,Python,Loops,我正在创建一个长度必须正好为140个字符的字符串。我必须使用带break语句的循环,字符串项取自给定的列表 最后,我设法达到了147个字符。有没有办法截断字符串 headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Re
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)))
如果您希望这样做,将把字符串截断为140个字符
如果您想这样做,将把字符串截断为140个字符。您的答案将以列表形式返回news\u ticker,但它必须是字符串。它允许您使用.append函数,但您可以像这样简单地连接字符串:
for headline in headlines:
news_ticker += headline + " "
if len(news_ticker) >= 140:
news_ticker = news_ticker[:140]
break
您的答案以列表的形式返回news\u ticker,但它必须是字符串。它允许您使用.append函数,但您可以像这样简单地连接字符串:
for headline in headlines:
news_ticker += headline + " "
if len(news_ticker) >= 140:
news_ticker = news_ticker[:140]
break
欢迎并感谢您发布答案。在你的答案中添加一些额外的注释以及它解决问题的原因,而不仅仅是发布代码片段,这是一个很好的实践。欢迎并感谢您发布答案。最好的做法是在答案中添加一些额外的注释以及为什么它可以解决问题,而不仅仅是发布代码片段。
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)
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))