I'm printing the return of a function but it doesn't work as intended

Viewed 45
FILE_NAME = "file.txt"
FILE_CONTENT = "Hello, and welcome to ",FILE_NAME,"!"

def FILE_WRITER(file_,content):
    FILE_OPEN = open(file_,"r+")

    FILE_OPEN.truncate(0)
    FILE_OPEN.write(''.join(FILE_CONTENT))
    FILE_OPEN.close()
    return "Fully changed the content of",file_,"to",content,"!"

print(FILE_WRITER(FILE_NAME,FILE_CONTENT))

When I execute the code above, it returns :

('Fully changed the content of', 'file.txt', 'to', ('Hello, and welcome to ', 'file.txt', '!'), '!')

I understand that my variables aren't well named. I tried to search on Google to answer my problem but the only thing I found is that I'm maybe using "tuples" and that I needed to do the transform it to a string

4 Answers
FILE_CONTENT = "Hello, and welcome to ",FILE_NAME,"!"

comma doesn't concatenate strings in python - it creates a tuple of three elements

try using

FILE_CONTENT = f"Hello, and welcome to {FILE_NAME}!" 
...
return f"Fully changed the content of {file_} to {content}!"

instead

P.S. and definitely change your naming convention

If you return more than 1 value from a function, it will be packed in a tuple.

For example:

>>> a=1,2,3
>>> print(a)
(1, 2, 3)

transform this line

FILE_CONTENT = "Hello, and welcome to ",FILE_NAME,"!"

into this

FILE_CONTENT = "Hello, and welcome to "+FILE_NAME+"!"

You return a tuple of values, and print with a tuple is not the same as print with multiple arguments. The latter prints the str of the individual arguments separated by space (by default), whereas the former just prints the str of the tuple.

>>> file_ = "<file_>"
>>> content = "<content>"
>>> print("Fully changed the content of",file_,"to",content,"!")  # individual parameters
Fully changed the content of <file_> to <content> !
>>> print(("Fully changed the content of",file_,"to",content,"!"))  # a single tuple
('Fully changed the content of', '<file_>', 'to', '<content>', '!')

You have two options: Either, keep returning the tuple, but unpack it to individual arguments when passing it to print:

>>> res1 = "Fully changed the content of",file_,"to",content,"!"
>>> print(*res1)
Fully changed the content of <file_> to <content> !

Or, probably preferable, join the different parts to a string before returning it (since that's probably what the function is supposed to return, a string) and then just print it:

>>> res2 = f"Fully changed the content of {file_} to {content}!"
>>> print(res2)
Fully changed the content of <file_> to <content>!

Or, lastly, just print in the function itself, instead of returning the string.

Related