簡體   English   中英

如何刪除列表中的多個字符?

[英]How can I remove multiple characters in a list?

有這樣的清單:

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

編輯

+-並不總是在前導 position; 他們可以在任何地方。

使用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']

使用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']

編輯:

如果您還在數字之間加上+- ,請使用str.translate()基於str.translate()解決方案

x = [i.replace('-', "").replace('+', '') for i in x]

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']

這些函數清除不需要的字符的字符串列表。

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']
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)

輸出:

其他人

你好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM