Saad
Saad

Reputation: 1360

Python: How to concatenate adjacent strings in list having combined length less than threshold?

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

Answers (2)

Rafael Neves
Rafael Neves

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

bereal
bereal

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

Related Questions