如何拆分和删除列表中的字符串?

时间:2019-05-05 05:52:41

标签: python

这是我的示例代码:

list1 = [{'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'},
     {'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot'
    }]

我需要将父级拆分为一个列表,并删除“ and”字符串。因此输出应如下所示:

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'Bartholomew Shoe'],
     {'name': 'Wisteria Ravenclaw', 'parents': ['Douglal Lyphe', 'Jackson', 'Pot']
    }]

请帮助我解决这个问题。

for people in list1:
    people['parents'] = people['parents'].split('and')

我不确定如何移动','字符串。

2 个答案:

答案 0 :(得分:1)

您应该在循环内使用people,而不是迭代器本身。

for people in list1:
    people['parents'] = people['parents'].split(' and ')

,然后在打印list1时,您得到:

[{'name': 'foobar', 'parents': ['John Doe', 'Bartholomew Shoe']}, {'name': 'Wisteria Ravenclaw', 'parents': ['Douglas Lyphe', 'Jackson Pot']}]

答案 1 :(得分:0)

扩展其他人说的话:您可能想对正则表达式进行拆分,以便于

  • 如果名称恰好包含该子字符串,则不要在and上进行拆分,
  • 您删除了and周围的空白。

像这样:

import re

list1 = [
  {'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'},
  {'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot'}
]

for people in list1:
    people['parents'] = re.split(r'\s+and\s+', people['parents'])

print(list1)