removing \xa0, \n, \t from python string
Question: I have a list item, that I've converted into a string:

    
    
    [u'\n                      Door:\xa0Novum          \t      ']
    

I need to remove everything so that Im left with

    
    
    Door:Novum
    

I have tried various methods:

    
    
    string = string.replace("\xa0", "")
    string.rstrip('\n')
    string.translate(string.maketrans("\n\t", ""))
    

I am obviously doing something wrong, but can't figure out what


Answer: You need to _store the return value_ ; strings are immutable so methods return
a new string with the change applied.

You can translate for all those characters, but use the `unicode` form of the
method:

    
    
    toremove = dict.fromkeys((ord(c) for c in u'\xa0\n\t '))
    outputstring = inputstring.translate(toremove)
    

I'm assuming you wanted to get rid of _spaces_ as well.

Demo:

    
    
    >>> inputstring = u'\n                      Door:\xa0Novum          \t      '
    >>> toremove = dict.fromkeys((ord(c) for c in u'\xa0\n\t '))
    >>> outputstring = inputstring.translate(toremove)
    >>> outputstring
    u'Door:Novum'
    

A better method still would be to use `str.split()`, then join again:

    
    
    outputstring = u''.join(inputstring.split())
    

`\xa0`, spaces, tabs and newlines are all included in what `str.split()` will
split on, as well as carriage returns.

Demo:

    
    
    >>> u''.join(inputstring.split())
    u'Door:Novum'
    

This is better because it is a _lot_ faster for this job than using
`str.translate()`!

    
    
    >>> import timeit
    >>> timeit.timeit('inputstring.translate(toremove)', 'from __main__ import inputstring, toremove')
    3.4527599811553955
    >>> timeit.timeit('u"".join(inputstring.split())', 'from __main__ import inputstring')
    0.5409181118011475
    

