9

有这样的清单:

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

如何以很好的方式删除 + 和 - ?

这可行,但我正在寻找更多的pythonic方式。

x = ['+5556', '-1539', '-99', '+1500']
n = 0
for i in x:
    x[n] = i.replace('-','')
    n += 1
n = 0
for i in x:
    x[n] = i.replace('+','')
    n += 1
print x

编辑

+并不-总是处于领先地位;他们可以在任何地方。

4

6 回答 6

20

使用string.translate(), 或用于 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 版本:

>>> 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']
于 2013-01-08T13:35:11.273 回答
16

使用str.strip()或最好str.lstrip()

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

使用list comprehension

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

使用map()

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

编辑:

如果您也介于数字之间,请使用@Duncan的基于解决str.translate()方案+-

于 2013-01-08T12:52:41.727 回答
11
x = [i.replace('-', "").replace('+', '') for i in x]
于 2013-01-08T12:52:27.950 回答
2

string.translate()仅适用于非 unicode 的字节字符串对象。我会使用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']
于 2014-04-28T13:21:02.657 回答
0

这些函数清除不需要字符的字符串列表。

lst = ['+5556', '-1539', '-99','+1500']
to_be_removed = "+-"

def remove(elem, to_be_removed):
    """ Remove characters from string"""
    return "".join([char for char in elem if char not in to_be_removed])

def clean_str(lst, to_be_removed):
   """Clean list of strings"""
   return [remove(elem, to_be_removed) for elem in lst]

clean_str(lst, to_be_removed)
# ['5556', '1539', '99', '1500']
于 2022-02-16T20:07:27.207 回答
-1
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)

输出 :

嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻

你好

于 2019-01-11T05:00:17.083 回答