zeurosis
zeurosis

Reputation: 183

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?

Upvotes: 0

Views: 9342

Answers (2)

Andrew Li
Andrew Li

Reputation: 57972

*x supplies much too many arguments to str() causing the error, and sep isn't an argument of str(). str() expects one object to be converted, and *x gives 5. Try this:

x = [1, 2, 3, 4, 5]
a = '_'.join(str(i) for i in x)
print(a) 

This will go through the list and join each element together with an underscore between.

Try it on IDEOne


You can also use map(function, sequence) to shorten the join(). The function being applied is str() to convert the numbers into string form, and to the x list. Here's with map():

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

Upvotes: 3

Karin
Karin

Reputation: 8610

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.

Upvotes: 4

Related Questions