Python/Django: How to remove extra white spaces & tabs from a string?

28,653

Solution 1

Split on any whitespace, then join on a single space.

' '.join(s.split())

Solution 2

>>> import re
>>> re.sub(r'\s+', ' ', 'some   test with     ugly  whitespace')
'some test with ugly whitespace'

Solution 3

I would use Django's slugify method, which condenses spaces into a single dash and other helpful features:

from django.template.defaultfilters import slugify

Solution 4

"electric guitar".split() will give you ['electric', 'guitar']. So will "electric \tguitar".

Share:
28,653

Related videos on Youtube

José Manuel Ramos
Author by

José Manuel Ramos

Updated on July 09, 2022

Comments

  • José Manuel Ramos
    José Manuel Ramos almost 2 years

    I'm building a website with Python/Django. Users submit tags. Each tag can contain multiple words. Each tag has an ID number. I want to make sure tags that are formatted slightly differently are still being recognized as the same tag.

    For example, if one user submitted the tag "electric guitar" and the other submitted "electric   guitar" (2 white spaces between the 2 words) I want to be able to recognize they are the same tag.

    How to I remove all the extra white spaces and tabs in this case? Thanks.

  • Chris Morgan
    Chris Morgan over 13 years
    Then you don't need to worry about things like case, either.
  • Marcus Whybrow
    Marcus Whybrow over 13 years
    I think that slugify is the best exhaustive solution, whereas things like splitting and joining, solves just this problem specifically. I like to leave it up to the Django devs.
  • Framester
    Framester about 13 years
    or newline = ' '.join(oldline.split()) ... is took me a minute to find that out as a newbie.
  • Andy Chase
    Andy Chase almost 11 years
    Note that this removes any whitespace before and after the string
  • Jorge Luis
    Jorge Luis over 2 years
    since this removes the spaces, it's not an proper answer to the problem of the question