zeurosis zeurosis - 1 year ago 64
Python Question

how to convert print output into variable/string with "more than 3 arguments"? (python 3)

Basically I'm trying to take the print output for my code and make it into a variable. I tried to do this by converting it to a string but it gave me an error saying "TypeError: str() takes at most 3 arguments (6 given)"

my code:

x = [1,2,3,4,5]
print(*x, sep='_') ##gives me the output "1_2_3_4_5"

#problem part:
a = str(*x, sep='_')
print(a) ##gives error

Is there either a way to convert the output to a string despite the "6 argument" thing or some other "str()"-like thing that would work?

Answer Source

You can convert the list of ints to a list of strings using map, then use join to bind them together:

x = [1, 2, 3, 4, 5]
a = '_'.join(map(str, x))
print(a)  # '1_2_3_4_5'

Note: Your code did not work because print does some work for you:

All non-keyword arguments are converted to strings like str() does and written to the stream.

So, print did the string conversion step for you. When you call str(), it expects only an object to convert to a string, with two optional keyword arguments (encoding and errors). By calling str(*x, sep='_'), you are passing in 5 arguments plus a separator, which is not a valid call.