1

I'm having some issues saving my lists to a file, the two ways in which I have tried have both yielded the undesired output.

The first way I tried was:

savefile.write(str(full_list))

returns:

[u'Smith', u'Malte Low', u'Day', u'George']

The other way I tried was:

for fitem in full_list:
    file.write(str(fitem))

returns:

SmithMalte LowDayGeorge

I am ideally looking for it to return:

Smith, Malte, Low, Day, George

I'm not quite sure how to use .join to make this work but it seems like the best option, I may be wrong.

Anyone got any ideas how I should be fixing this, it would be much appreciated.

Thanks in advance - Hy

2 Answers 2

2

You can use.

 ", ".join(full_list)

And then write the results to the file.

See the snippet -

>>> full_list = [u'Smith', u'Malte Low', u'Day', u'George']
>>> print ", ".join(full_list)
Smith, Malte Low, Day, George

EDIT - Just saw that you wanted a comma between Malte Low, then, you can just do

>>> from itertools import chain
>>> ", ".join(chain.from_iterable(map(str.split, full_list)))
u'Smith, Malte, Low, Day, George'
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't know I could do that. Thanks. :)
1

Given the list

[u'Smith', u'Malte Low', u'Day', u'George']

You may try

savefile.write(','.join(full_list))

But that would simply return

Smith,Malte Low,Day,George

which may not be what you wan't as your desired output, delimits words and not the items by ','

So you may want to do

  • join with spaces
  • followed by splitting the resultant string by spaces
  • and then join back by comma

    savefile.write(','.join(' '.join(full_list).split()))
    

But then you have to iterate multiple times. To perform the operation on a single iteration, you can use itertools.chain.from_iterable

from itertools import chain
savefile.write(','.join(itertools.chain.from_iterable(e.split()
                       for e in full_list)))

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.