gpt4 book ai didi

python - 在Python中将字符串按空格分割成最大长度的子字符串

转载 作者:行者123 更新时间:2023-12-02 06:09:25 26 4
gpt4 key购买 nike

我有一个像这样的字符串:

Trump, Defending Himself After Flynn Guilty Plea, Says FBI Is in 'Tatters' | CVS to Buy Aetna for $69 Billion in a Deal that May Reshape the Health Industry | Joy Reid Apologizes for Past Anti-Gay Articles: 'Insensitive, Tone Deaf and Dumb' | California 18-year-old confesses to molesting dozens of children | Bill Belichick Apologizes for Rob Gronkowski's Late Hit, Calls It 'Bulls--t' | Met Opera Suspends James Levine After New Sexual Abuse Accusations | Like it or not, Alabama brings legitimacy to this year's College Football Playoff | Trump's campaign: Big Macs, screaming fits and constant rivalries | Manhattan equity director mauled to death by shark while scuba diving off Costa Rican coast | Man Stabs Two in Queens, Then Drives Into Their Helpers, Police Say | Here's how the Rangers might be able to separate themselves from other contenders for Shohei Ohtani | Alabama's Disdain for Democrats Looms Over Its Senate Race | Billy Bush confirms it was Trump's voice on 'Access Hollywood' tape: 'Yes, Donald Trump, you said that' | Andy Reid: Darrelle Revis didn't play in second half because he played a lot in first half | Geno Smith calls out 'coward' Rex Ryan: 'I saved his job' | Jimmy Garoppolo gives the 49ers exactly what they need, plus more Week 13 notes | Enter the 'Petro': Venezuela to Launch Oil-Backed Cryptocurrency | Wiring blamed in failed Pontiac Silverdome implosion | McConnell predicts unpopular tax bill will be a winning issue for GOP | Broncos drop eighth straight in ugly loss to Dolphins |

这是从 Google 新闻 RSS Feed 解析的新闻标题列表。我通过串行方式将数据发送到 LCD,该 LCD 有 2 行,每行 16 个字符。目前,我将字符串拆分为 32 个字符部分,然后将每个部分显示固定的时间长度。这样做的问题是,在大多数情况下,它仅显示最后一个单词的一部分,在某些情况下,仅显示第一个单词的一部分,具体取决于字符串的拆分方式。那么,如何通过空格分割字符串,以防止分割单词,并且仍然尝试小于 32 个字符的限制。

使用上述文本的示例是:

第一行:特朗普,之后为自己辩护

第二行:弗林认罪,称联邦调查局是

诸如此类。

最佳答案

您可以创建自己的定义并定义限制,如下所示,并且可以迭代列表。

str = "Trump, Defending Himself After Flynn Guilty Plea, Says FBI Is in 'Tatters'"

def split_string(str, limit, sep=" "):
words = str.split()
if max(map(len, words)) > limit:
raise ValueError("limit is too small")
res, part, others = [], words[0], words[1:]
for word in others:
if len(sep)+len(word) > limit-len(part):
res.append(part)
part = word
else:
part += sep+word
if part:
res.append(part)
return res

print split_string(str=str, limit=32)

输出:

['Trump, Defending Himself After', 'Flynn Guilty Plea, Says FBI Is', "in 'Tatters'"]

关于python - 在Python中将字符串按空格分割成最大长度的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47625950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com