我有一个列表,其中包含各种内容,看起来类似于:
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
我目前正在像这样迭代它:
def myFunction(exList)
result = []
yElement = exList[0]
for ch in yElement:
if ch in SYMBOLS: #I have a list of symbols saved globally in another area
exList.remove(ch)
result = exList
我尝试了其他几种方法来解决这个问题,但一无所获。我的问题是如何遍历列表元素并删除所有符号,然后继续下一个列表元素?任何帮助将不胜感激。
SYMBOLS = '{}()[].,:;+-*/&|<>=~'
我想以这样的列表结束:
['JM', 'the quick brown fox', 'word']
请您参考如下方法:
>>> SYMBOLS = '{}()[].,:;+-*/&|<>=~$1234567890'
>>> strings = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
>>> [item.translate(None, SYMBOLS).strip() for item in strings]
['JM', 'the quick brown fox', 'word']
如果您希望第一个字符串看起来像JM,您还必须将数字添加到SYMBOLS,并且您还缺少$ 字符。
来自文档:
S.translate(table [,deletechars]) -> string
Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.
你也可以用正则表达式来做,但如果你只需要一个简单的替换,这样会更干净。
