0

How do I split individual strings in a list?

data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')

Return:

print(data)
('Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill')
1
  • 1
    and your attempts are? Commented Aug 8, 2019 at 2:18

3 Answers 3

3

One approach, using join and split:

items = ' '.join(data)
terms = items.split(' ')
print(terms)

['Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill']

The idea here is to generate a single string containing all space-separated terms. Then, all we need is a single call to the non regex version of split to get the output.

Sign up to request clarification or add additional context in comments.

2 Comments

I like this approach. Do you foresee any problems coming from it, i.e. it solves the problem as stated, but maybe doesn't generalize as well as some other approach?
@ToddBurus It might not be the most space efficient method, because it generates a big ugly string.
1
data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')
data = [i.split(' ') for i in data]
data=sum(data, [])
print(tuple(data))
#('Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill')

Comments

0

You can use itertools.chain for that like:

Code:

it.chain.from_iterable(i.split() for i in data)

Test Code:

import itertools as it

data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')
print(list(it.chain.from_iterable(i.split() for i in data)))

Results:

['Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.