Python拆分包含字符(例如/,[])的列表元素并创建新元素

2024-09-25 00:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下列表:

test = ['bla bla','affect /affected / affecting']
print(test)

我想在列表中创建新的元素,通过分隔一个元素,但通过“/”符号分隔

例如,这种情况下的期望输出:

test_new = ['bla bla','affect','affected','affecting']

我该怎么做

编辑:列表可以有多个元素,但并非所有元素都有“/”符号


Tags: test元素编辑列表new符号情况print
2条回答

您可以使用列表理解和'/'strip上的split来删除空格(假设您有多个字符串,作为一个列表):

[j.strip() for i in test for j in i.split('/')]
# ['affect', 'affected', 'affecting']
testEntry=test[0]
testEntry=test.replace(' ','')
test=testEntry.split('/')

相关问题 更多 >