Skip to main content
 首页 » 编程设计

python之如何按另一个列表中出现的字符拆分字符串

2025年05月04日11tintown

我试图在看到我的符号列表中的一个符号(这是一个很大的列表)时立即拆分一个字符串。现在我想知道的是,作为一个新的 python 用户,有没有一种方法不是 split 方法,我可以告诉它在看到 symbolList 的任何成员时立即拆分? 这是一个例子:

symbolList=[',' , '&' , '8' , '9' , '.'] 
words = ['ha,di' , 'dea&r'] 
for word in words : 
    for i in word : 
         if i in symbolList: 
             #a method which splits the string by the symbol 

我想像这样:

newWords=['ha' , 'di' , 'dea' ,'r'] 

请您参考如下方法:

尝试使用 rsplit

words = ['ha,di' , 'dea&r','1.2'] 
for i in words: 
    print re.split(',|&|8|9|\.', i) 
 
#output 
 
['ha', 'di'] 
['dea', 'r'] 
['1', '2'] 

对于非常大的列表

import re 
symbolList=[',' , '&' , '8' , '9' , '.'] 
regex = '|'.join(map(re.escape, symbolList)) 
 
words = ['ha,di' , 'dea&r','1.2'] 
for i in words: 
    print re.split(regex, i)