Python/Django: How to remove extra white spaces & tabs from a string?
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"
.
Related videos on Youtube
José Manuel Ramos
Updated on July 09, 2022Comments
-
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 over 13 yearsThen you don't need to worry about things like case, either.
-
Marcus Whybrow over 13 yearsI 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 about 13 yearsor newline = ' '.join(oldline.split()) ... is took me a minute to find that out as a newbie.
-
Andy Chase almost 11 yearsNote that this removes any whitespace before and after the string
-
Jorge Luis over 2 yearssince this removes the spaces, it's not an proper answer to the problem of the question