Search code examples
pythonfwrite

How to write to file without parenthesis in python


When i write to file my results:

output=knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i]
value=str(output)
o.write(value+'\n')

I get:

(0.05, 0.05, 0.166667, -0.8513056, 0.9881956035137526)
(0.05, 1.05, 0.166667, -0.8513056, 0.011652226336523394)
(0.05, -0.9500000000000002, 0.166667, -0.8513056, 0.00015217014972403685)

How to write to file so it doesn't add brackets?


Solution

  • 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]