Django recipe: Remove newlines from a text block

I like to keep a Django app called "toolbox" or "utils" in my projects where I store odds and ends. One recent addition is this quickie function for removing any newlines characters found in a block of text.

One place I find it useful is when I'm looking to dump scraped or user-submitted data to a spreadsheet or CSV.

Imagine a file like "toolbox/templatetags/misc_tags.py" within a Django project that looks like so:

from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
from django.utils.text import normalize_newlines

register = template.Library()

def remove_newlines(text):
    """
    Removes all newline characters from a block of text.
    """
    # First normalize the newlines using Django's nifty utility
    normalized_text = normalize_newlines(text)
    # Then simply remove the newlines like so.
    return mark_safe(normalized_text.replace('\n', ' '))
remove_newlines.is_safe = True
remove_newlines = stringfilter(remove_newlines)
register.filter(remove_newlines)

It then can be called in the template environment...

{% load misc_tags %}

{{ foo|remove_newlines }}

...or in the shell.

>>> from toolbox.templatetags.misc_tags import remove_newlines
>>> text = 'Line one\nLine two\rLine three\r\nLine four'
>>> remove_newlines(text)
'Line one Line two Line three Line four'

That's the whole trick. If there's something I screwed up—a common event—feel free to let me know.

This is a post made on , 8 years, 2 months ago.

It is filed with other posts about car.

Comments

en
195