How to write to file without parenthesis in python

一笑奈何 提交于 2019-12-06 14:17:05

Instead of

value = str(output)

you can do

value = ', '.join(map(str, output))

What you see is the string representation of a tuple. It's there because you called str on it.

What the str.join method does is join an iterable (e.g. a tuple or a list) of strings, using the string that it's called on as a delimiter (here ', ' is the delimiter and map(str, output) is the iterable of strings.) into a single string. map applies a function to each element of an iterable. In this case, str is applied to each element of output, so that we have an iterable of strings, rather than float numbers.

Alternatively (a bit hacky) you can just strip off the parentheses from the value that you have:

value = str(output)[1:-1]

You can also use the csv module:

import csv

with open('file.txt', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    output = knew[i][0], knew[i][1], knew[i][2], eigenval[k], group[i]
    writer.writerow(output)
value = "{0}, {1}, {2}, {3}, {4}".format(knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i])
o.write(value)

Using format function of str objects is a better approach. And more efficient too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!