Login

Make a string a fixed-width

Author:
adamfast
Posted:
June 12, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

This snippet is a template filter based on "truncate letters" only it will either truncate or pad a string to ensure the output is always a set width.

 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
@register.filter
def fixedwidth(value, arg):
    """
    Truncates or pads a string to be a certain length
    
    Argument: Desired length of string
    """

    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 - 3]
        if not truncated.endswith('...'):
            truncated += '...'
        return truncated
    if len(value) <= length:
        padded = value
        spaces_needed = (length - len(value)) + 1
        for space_needed in range(1, spaces_needed):
            padded = "%s " % padded
        return padded

    return value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

derelm (on June 13, 2007):

is probably only ment for non-html output (or output styled like 'white-space: pre'). if used outside that context, don't forget to replace " " with "&nbsp;" (and maybe "..." with "&hellip;" if you're a typography nerd)

nothing wrong with that, just looks complicated.

[...]
if len(value) <= length:
    spaces_needed = length - len(value)
    return value + spaces_needed * " "

return value

#

Please login first before commenting.