Login

Make a string a fixed-width

Author:
adamfast
Posted:
June 12, 2007
Language:
Python
Version:
.96
Tags:
text fixed-width
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. truncate letters by trbs 8 years, 3 months ago
  2. Truncate filter by zalun 6 years, 2 months ago
  3. truncate by alfor 8 years, 3 months ago
  4. Truncate string after a given number of chars keeping whole words by rix 6 years, 6 months ago
  5. Truncate words by characters by trodrigues 7 years, 1 month 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.