0

How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
  • Does this answer your question? [python how to split text already in a list](https://stackoverflow.com/questions/44085616/python-how-to-split-text-already-in-a-list) – Abercrombie Feb 19 '20 at 09:18

6 Answers6

3

Well you can do that easily but first you should read what does the split function exactly do.

newList = []
for i in text:
    words = i.split(',')
    newList.extend(words)
print(newList)

Here are some useful information, Python list extend, Iterating over a list.

Plus, There is no method called replace for lists, this method works for Strings.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
2
your_list = [ x for sublist in text for x in sublist.split(',') ]
Błotosmętek
  • 12,717
  • 19
  • 29
1

There is no replace function for a list. I guess what you want is to split on comma:

text = ['a,b', 'c,d']
result = []
for i in text:
  result.extend(i.split(','))

Note the second change I did is to print i - the thing that iterates as opposed to the whole text. Additionally I am calling extend on the result to produce a single list.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

One more approach:

text = ['a,b', 'c,d']
text = ','.join(text)
text = text.split(',')
print(text)
# ['a', 'b', 'c', 'd']
Giannis Clipper
  • 707
  • 5
  • 9
1

You could do to the following:

text = ['a,b', 'c,d']
text_str = "".join(text).replace(",", "")
arr = [c for c in text_str]

its a bit verbose, but those are the steps

pydjango
  • 41
  • 3
1

Maybe this?

>>> from itertools import chain
>>> text = ['a,b', 'c,d']
>>> list(chain(*[item.split(',') for item in text]))
['a', 'b', 'c', 'd']
alvas
  • 115,346
  • 109
  • 446
  • 738