0

Given a title and a max_length, what would be the best way to shorten the title? The following is what I had in mind:

def shorten_title(title, max_length):
    if len(title) > max_length:
        split_title = title.split()
        length = len(title)
        n = 1
        while length > max_length:
            shortened_title = split_title[:length(split_title)-n]
            n+=1
        return shortened_title
    else:
        return title
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

4
>>> shorten_title = lambda x, y: x[:x.rindex(' ', 0, y)]
>>> shorten_title('Shorten title to a certain length', 20)
'Shorten title to a'

That should be enough if breaking on a space is all you need. Otherwise, there are several other posts on more complex methods, like: Truncate a string without ending in the middle of a word .

Update to address comment from okm:

To handle edge cases, like finding no spaces before max_length, address them explicitly:

def shorten_title2(x, y):
    if len(x) <= y:
        return x
    elif ' ' not in x[:y]:                                          
        return x[:y]
    else:
        return x[:x.rindex(' ', 0, y + 1)]
Community
  • 1
  • 1
Mzzzzzz
  • 4,770
  • 7
  • 30
  • 47
  • This code has some problems: 1. it fails string not having space 2. need tweak on edge condition, for example `shorten_title('Shorten title to a certain length', 26)` does not give `'Shorten title to a certain'` which is exactly 26 chars long. – okm Apr 25 '12 at 12:12
1
def shorten_title(title, max_length):
    return title[:max_length + 1]

How about that?

OK, without splitting up words, you want this:

import string

def shorten_title(title, max_length):
    if len(title) > max_length:
        split_title = title.split()
        length = len(title)
        n = 1
        while length > max_length:
            shortened_title = split_title[:-n]
            n = n + 1
            length = len(string.join(shortened_title))
        if shortened_title == []:
            return title[:max_length + 1]
        return string.join(shortened_title)
    else:
        return title

Here are the results I see:

print shorten_title("really long long title", 12)
print shorten_title("short", 12)
print shorten_title("reallylonglongtitlenobreaks", 12)

really long
short
reallylonglon

I tried to keep the code and logic similar to the original poster, but there are certainly more pythonic ways of doing this.

jgritty
  • 11,660
  • 3
  • 38
  • 60
0
def shorten_title(title, max_length):
    title_split = split(title)
    out = ""
    if len(title_split[0]) <= max_length:
        out += title_split[0]
    for word in title_split[1:]:
        if len(word)+len(out)+1 <= max_length:
            out += ' '+word
        else:
            break
    return out[1:]

Try that :)

SudoNhim
  • 580
  • 4
  • 17