![](/img/trans.png)
[英]How to remove special character in a list of string and split it into separate elements
[英]How to split and remove a string in a list?
这是我的示例代码:
list1 = [{'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'},
{'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot'
}]
我需要将父级拆分为一个列表,并删除“和”字符串。 因此输出应如下所示:
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')
我不确定如何移动','字符串。
您应该在循环中使用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']}]
扩展别人的看法:您可能希望拆分正则表达式,以便
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.