0

I have a list containing some tuples as well as normal strings like below :

a = ['sore', ('PHENOMENA', 'sore'), 'throat', ('ANATOMY', 'throat'), 'and',   'leg', ('ANATOMY', 'leg')]

I want to write it in a space separated text file in a format like:

sore ('PHENOMENA', 'sore') throat ('ANATOMY', 'throat') and leg ('ANATOMY', 'leg')
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Koushik Khan
  • 179
  • 2
  • 12

3 Answers3

5

Something like this?

>>> ' '.join(map(str, a))
"sore ('PHENOMENA', 'sore') throat ('ANATOMY', 'throat') and leg ('ANATOMY', 'leg')"

map(str, a) convert all elements in a to string object, then ' '.join() join them by space and returns a string object.

You can also use a list comprehension instead of map():

>>> ' '.join(str(i) for i in a)
"sore ('PHENOMENA', 'sore') throat ('ANATOMY', 'throat') and leg ('ANATOMY', 'leg')"
Community
  • 1
  • 1
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • @Koushik: So if an answer is correct, remember *accept* it (you can do it after 2 mins). You can check the [tour] for details. – Remi Guan Jan 19 '16 at 06:02
1

Try this

a = ['sore', ('PHENOMENA', 'sore'), 'throat', ('ANATOMY', 'throat'), 'and',   'leg', ('ANATOMY', 'leg')]
s = ' '.join(str(part) for part in a)    
with open('outfile.txt', 'w') as outfile:
    outfile.write(s)

In the directory where you run this code you will get a file named 'outfile.txt' containing this:

sore ('PHENOMENA', 'sore') throat ('ANATOMY', 'throat') and leg ('ANATOMY', 'leg')
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
0

You can join each element of the list by a space via ' '.join(). The caveat is you need to convert everything to string, including the tuples, which you can do using map.

One possible way of coding is as simple as:

with open('file.txt', 'w') as f:
    f.write(' '.join(map(str, a)))
sal
  • 3,515
  • 1
  • 10
  • 21