Writing


#1

Hiya. As we are dealing with integers, why do we have "str" in the penultimate line as in
my_file.write(str(i) + "\n")
Thanking you in advance

# Add your code below!
  my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "w")
my_file.write("Data to be written" + "\n")
for i in my_list:
    my_file.write(str(i) + "\n")
my_file.close()

<do not remove the three backticks below>


#2

well, we want to write all the numbers to a separate line so we use "\n" which is a string contain new line character, if we wouldn't convert i to string you would get:

TypeError: unsupported operand type(s) for +: 'int' and 'str'


#3

And in the documentation
https://docs.python.org/3.3/tutorial/inputoutput.html
f.write(string) writes the contents of string to the file, returning the number of characters written.

f.write('This is a test\n')
15

To write something other than a string, it needs to be converted to a string first:

value = ('the answer', 42)
s = str(value)
f.write(s)
18


#4

Aaah I see, thanks mate; so, the string "\n " has precedence? My take was that the str refers/d to the items and if this were not the case, I would have expected the str to be outside the first set of brackets,(parenthesis)


#5

Thank you for that. Does it mean that the numbers, 1 - 100, generated are strings? If so why are they not in single quotes?. Excuse my ignorance. I shall mug it up from your link . Thanks


#6

no, but i is of type integer and "\n" is of type string. trying to add string and integer together doesn't work. So we need convert i to string, so we can concatenate i and new line so all numbers are printed on separate lines.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.