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

后端 未结 6 2114
天命终不由人
天命终不由人 2020-12-29 21:59

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 sl

相关标签:
6条回答
  • 2020-12-29 22:42

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

    0 讨论(0)
  • 2020-12-29 22:45

    This function removes everything which is not digit in a string. I use it all over the place.

    def parseInt(string):
        if isinstance(string, (str, int, unicode)):
            try:
                digit = int(''.join([x for x in string if x.isdigit() ]))
            except ValueError:
                return False
            else:
                return digit
        else:
            return False   
    
    0 讨论(0)
  • 2020-12-29 22:57

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

    from django.template.defaultfilters import slugify
    
    0 讨论(0)
  • 2020-12-29 23:00

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

    ' '.join(s.split())
    
    0 讨论(0)
  • 2020-12-29 23:00

    There could be many white spaces like below:

    var = "         This      is the example  of how to remove spaces   "
    

    Just do simple task like, use replace function:

    realVar = var.replace(" ",'')
    

    Now the outpur would be:

    Thisistheexampleofhowtoremovespaces 
    

    Just Chill......... :-)

    0 讨论(0)
  • 2020-12-29 23:02
    >>> import re
    >>> re.sub(r'\s+', ' ', 'some   test with     ugly  whitespace')
    'some test with ugly whitespace'
    
    0 讨论(0)
提交回复
热议问题