对字符串的长度求和并连接,使得字符串的长度满足条件
假设我有一个字符串列表,我想用它们创建一条推文。例如:
# should be two tweets total
this_list = ["Today is monday tomorrow is tuesday the next" ,"will be friday and after that", "saturday followed by sunday", "this month is march the next", "april after that may followed", "by june then july then we", "have august then", "september and october finishing", "the year with november and december" ]
我想要的输出将与此类似(当然存储在列表中):
tweet 1: 'Today is monday tomorrow is tuesday the next will be friday and after that saturday followed by sunday this month is march the next april'
tweet 2: 'after that may followed by june then july then we have august then september and october finishing the year with november and december'
我尝试使用 while 循环来实现此目的,但我不确定循环是否正常工作...
out = [] # empty list
s = 0 # counter
tweet = "" # string to add too
while s < 140:
for x in this_list:
tweet += x
s += len(x)
out.append(tweet)
print(len(out))
Suppose i have a list of strings and I wanted to make a tweet out of them. for example:
# should be two tweets total
this_list = ["Today is monday tomorrow is tuesday the next" ,"will be friday and after that", "saturday followed by sunday", "this month is march the next", "april after that may followed", "by june then july then we", "have august then", "september and october finishing", "the year with november and december" ]
my desired output would be similar to this (stored in a list of course):
tweet 1: 'Today is monday tomorrow is tuesday the next will be friday and after that saturday followed by sunday this month is march the next april'
tweet 2: 'after that may followed by june then july then we have august then september and october finishing the year with november and december'
I have tried to use a while loop to achieve this but I am not sure the loop is working correctly...
out = [] # empty list
s = 0 # counter
tweet = "" # string to add too
while s < 140:
for x in this_list:
tweet += x
s += len(x)
out.append(tweet)
print(len(out))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终使用了一个包含长度和文本的元组列表;然后对长度求和,直到满足 140 个字符。
I ended up using a list of tuples that held the length and text; then summing through the lengths until 140 characters met.
这不是最Pythonic 的方法。但它非常清晰,并以可见的方式分解了逻辑:
This is not the most pythonic way of doing this. But it is pretty clear and breaks down the logic in a visible manner: