Convert a tuple of floats and text to one line

I am trying to convert a tuple of 2 floats and 3 pieces of text to one line, so I can use it in a .write () file because it does not accept tuples.

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

      

whenever i try to run the program it gives me this

    test.write(testr)
TypeError: must be str, not tuple

      

+3


source to share


4 answers


Unlike other answers, this will take your suggested tuple:

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(" ".join(str(i)for i in testr))
test.close()

      

Since only the third line is different from your code, here's an explanation:

first str(i)for i in testr

:



the built-in for

-loop is known in python as a list . It just iterates over your tuple testr

, returning values ​​one by one. str(i)

is a typecast, it tries to convert i

to a string. This is necessary because in your tuple some elements are String

-type and some variables are some type of number, probably Float

or Integer

. See str () , float () and int () for further reading.

Then " ".join(...)

:

This is a string function that takes a list or tuple of strings and, like the name sugests, concatenates it together, separating the substring it affects by the part before period ( " "

). This has always seemed a little odd to me, or perhaps inside out, but it's a very useful feature nonetheless!

Hope this helps!

+1


source


Use format

:



testr = 'you went {} mph and stopped in {} meters'.format(speed, stop)

      

+2


source


Convert it to String

test.write(str(testr))

      

0


source


Fortunately, python 3.6 makes this very easy and accessible to us:

testr = f'you went {speed} mph and stopped in {stop} metres'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

      

otherwise, the same happens when used string.format(*args)

as stated in the other answer.

0


source







All Articles