gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:03 26 4
gpt4 key购买 nike

我试图在看到我的符号列表中的一个符号(这是一个很大的列表)时立即拆分一个字符串。现在我想知道的是,作为一个新的 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)

关于python - 如何按另一个列表中出现的字符拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com