Login

truncate letters

Author:
trbs
Posted:
March 23, 2007
Language:
Python
Version:
.96
Tags:
filter truncate letters
Score:
1 (after 1 ratings)

filter for truncating strings similar to truncatewords only with letters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django import template

register = template.Library()

@register.filter(name='truncateletters')
def truncateletters(value, arg):
    """
    Truncates a string after a certain number of letters

    Argument: Number of letters to truncate after
    """
    def truncate_letters(s, num):
        "Truncates a string after a certain number of letters."
        length = int(num)
        letters = [l for l in s]
        if len(letters) > length:
            letters = letters[:length]
            if not letters[-3:] == ['.','.','.']:
                letters += ['.','.','.']
        return ''.join(letters)

    try:
        length = int(arg)
    except ValueError: # invalid literal for int()
        return value # Fail silently
    if not isinstance(value, basestring):
        value = str(value)
    return truncate_letters(value, length)

More like this

  1. Truncate Characters Filter (simple) by leahculver 8 years, 3 months ago
  2. Make a string a fixed-width by adamfast 8 years, 1 month ago
  3. truncatestring filter by pigletto 6 years, 4 months ago
  4. Truncate filter by zalun 6 years, 3 months ago
  5. truncate by alfor 8 years, 3 months ago

Comments

simonbun (on March 23, 2007):

Why not rewrite this as:

@register.filter
def truncateletters(value, arg):
"""
Truncates a string after a certain number of letters

Argument: Number of letters to truncate after
"""

try:
    length = int(arg)
except ValueError: # invalid literal for int()
    return value # Fail silently
if not isinstance(value, basestring):
    value = str(value)

if len(value) > length:
    truncated = value[:length]
    if not truncated.endswith('...'):
        truncated += '...'
    return truncated

return value

#

trbs (on April 1, 2007):

yes :)

it's very rough and the inline function is not nice. have to try this out in my own app, surely your rewrite reads much better.

#

ershadul (on September 16, 2009):

when I will write truncateletters:20 , it means that I want to show atmost 20 letters. But the above code with add 3 dots if the length of the value is greater than 20. That is ultimate it will show 23 letters. I think one statement can be added after line no. 18 The code is:

  1. ....

letters = letters[:-3]

....

#

Please login first before commenting.