How can I remove multiple characters in a list?

后端 未结 5 888
天命终不由人
天命终不由人 2020-12-11 04:56

Having such list:

x = [\'+5556\', \'-1539\', \'-99\',\'+1500\']

How can I remove + and - in nice way?

This works but I\'m looking f

相关标签:
5条回答
  • 2020-12-11 05:22
    x = [i.replace('-', "").replace('+', '') for i in x]
    
    0 讨论(0)
  • 2020-12-11 05:22
    basestr ="HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE"
    
    def replacer (basestr, toBeRemove, newchar) :
        for i in toBeRemove :
            if i in basestr :
            basestr = basestr.replace(i, newchar)
        return basestr
    
    
    
    newstring = replacer(basestr,['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'], "")
    
    print(basestr)
    print(newstring)
    

    Output :

    HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE

    helloo

    0 讨论(0)
  • 2020-12-11 05:23

    Use str.strip() or preferably str.lstrip():

    In [1]: x = ['+5556', '-1539', '-99','+1500']
    

    using list comprehension:

    In [3]: [y.strip('+-') for y in x]
    Out[3]: ['5556', '1539', '99', '1500']
    

    using map():

    In [2]: map(lambda x:x.strip('+-'),x)
    Out[2]: ['5556', '1539', '99', '1500']
    

    Edit:

    Use the str.translate() based solution by @Duncan if you've + and - in between the numbers as well.

    0 讨论(0)
  • 2020-12-11 05:36

    string.translate() will only work on byte-string objects not unicode. I would use re.sub:

    >>> import re
    >>> x = ['+5556', '-1539', '-99','+1500', '45+34-12+']
    >>> x = [re.sub('[+-]', '', item) for item in x]
    >>> x
    ['5556', '1539', '99', '1500', '453412']
    
    0 讨论(0)
  • 2020-12-11 05:39

    Use string.translate(), or for Python 3.x str.translate:

    Python 2.x:

    >>> import string
    >>> identity = string.maketrans("", "")
    >>> "+5+3-2".translate(identity, "+-")
    '532'
    >>> x = ['+5556', '-1539', '-99', '+1500']
    >>> x = [s.translate(identity, "+-") for s in x]
    >>> x
    ['5556', '1539', '99', '1500']
    

    Python 2.x unicode:

    >>> u"+5+3-2".translate({ord(c): None for c in '+-'})
    u'532'
    

    Python 3.x version:

    >>> no_plus_minus = str.maketrans("", "", "+-")
    >>> "+5-3-2".translate(no_plus_minus)
    '532'
    >>> x = ['+5556', '-1539', '-99', '+1500']
    >>> x = [s.translate(no_plus_minus) for s in x]
    >>> x
    ['5556', '1539', '99', '1500']
    
    0 讨论(0)
提交回复
热议问题