Basically I have a string like this:
names = "John Doe Jane Doe John Smith Jane Smith".
I want to convert it to look like:
outs = ["John Doe", "Jane Doe", "John Smith", "Jane Smith"].
Thanks.
Basically I have a string like this:
names = "John Doe Jane Doe John Smith Jane Smith".
I want to convert it to look like:
outs = ["John Doe", "Jane Doe", "John Smith", "Jane Smith"].
Thanks.
Here is another solution, it uses more_itertools
to simplify a little bit. It's yield slices
of length n
from the sequence seq.
from more_itertools import sliced # import this lib first
# your names:
outs = [' '.join(n) for x in sliced(names.split(), 2) ]
print(outs)
Output:
['John Doe', 'Jane Doe', 'John Smith', 'Jane Smith']
Consider using regular expressions to solve this.
>>> names = "John Doe Jane Doe John Smith Jane Smith"
>>> re.findall(r'\b[a-zA-Z]+\s+[a-zA-Z]+\b', names)
['John Doe', 'Jane Doe', 'John Smith', 'Jane Smith']
>>>
Alternatively, and without imports, you could use a list comprehension, which is very pythonic
>>> [' '.join(x.split()[i:i+2]) for i in range(0,len(x.split()),2)] #list comprehension
['Jane Doe', 'John Doe']
If you only need to iterate over it once, a generator may be more suitable
>>> x="Jane Doe John Doe"
>>> print(' '.join(x.split()[i:i+2]) for i in range(0,len(x.split()),2)) #generator object
>>> for i in (' '.join(x.split()[i:i+2])for i in range(0,len(x.split()),2)): #iterating through the generator
print(i)
Jane Doe
John Doe
<generator object <genexpr> at 0x0000000000000000>
If you want to perform other transformations on the data, python has set comprehensions and dictionary comprehensions available.
>>> y='John Doe Jane Doe John Doe'
>>> {' '.join(y.split()[i:i+2]) for i in range(0,len(y.split()),2)}
{'John Doe', 'Jane Doe'} #set comprehension (to remove duplicates)
>>> {i//2:' '.join(x.split()[i:i+2]) for i in range(0,len(x.split()),2)} #dictionary comprehension (keys arbitrary)
{0: 'Jane Doe', 1: 'John Doe'}