John
John

Reputation: 87

Most Pythonic and efficient to join list of strings until the length gets too high

Assume I am creating a checkout system for a store. This is a list of the products:

products = ["Apple", "Banana", "Cherry", "Durian"]

And I want to join them with commas. So, I can use this:

", ".join(products) # Returns "Apple, Banana, Cherry, Durian"

What if I want to limit the length of the output string? Say, I want to output "Apple, Banana…" if the final string is longer than 20 characters? The problem is, I want to prevent the names from being cut, so I don't want "Apple, Banana, Cher…". In some cases, the strings in products may contain commas, so I don't want to split the string with commas.

Upvotes: 3

Views: 1157

Answers (1)

Synthaze
Synthaze

Reputation: 6090

products = ["Apple", "Banana", "Cherry", "Durian"]

string = products[0]

for v in products[1:]:
    if len(string) + len(', ') + len(v) <= 20:
        string = string + ', ' + v
    else:
        string = string + '...'
        break

print(string)

Output:

Apple, Banana...

Upvotes: 8

Related Questions