Reputation: 1360
I would like to merge/concatenate adjacent strings in a list whose combined length is below a threshold. The concatenated string should have a single space separating the individual strings.
For example, if the list contains the following strings:
list = ['This', 'is', 'a', 'sample', 'example']
and the threshold is 10, then the list should be modified to:
list = ['This is a', 'sample', 'example']
Edit: I am using a for loop comparing adjacent strings.
for i in range(1, len(list)):
if len(list[i]) + len(list[i-1]) < 10:
list[i-1] = list[i-1]+' '+list[i]
del list[i]
but this gives IndexError: list index out of range
because the loop counter has been initialized to the initial len(list)
.
Upvotes: 2
Views: 928
Reputation: 467
import re
import textwrap
sample = ['This', 'is', 'a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']
sample_join = " ".join(sample)
textwrap.wrap(sample_join, width=10, break_long_words=False)
['This is a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']
Upvotes: 1
Reputation: 34272
One (a bit lazy) way to do this is using the textwrap
module from the standard library:
>> import textwrap
>> textwrap.wrap('This is a sample example', width=10)
['This is a', 'sample', 'example']
(If your text is already split into words, you'll have to join it back first, which is a bit wasteful, but still works.)
Upvotes: 2