简体   繁体   中英

How to split and remove a string in a list?

Here's my example code:

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

I need to split parent into a list and remove 'and' string. So the output should look like this:

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

Please help me figure this out.

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

I'm not sure how to move that ', ' string.

You should use people inside loop, not the iterator itself.

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

and then when you print list1 , you get:

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

Expanding on what others said: You may want to split on a regular expression so that

  • you don't split on and in case a name happens to contain that substring,
  • you remove the whitespace around and .

Like so:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM