0

Python: .join method

def func(x): for i in range(x): yield i**2 print(",".join(list(func(3)))) # outputs TypeError: sequence item 0: expected str instance, int found The join() method takes all items in an iterable and joins them into one string. So I instead tried converting the func to a string instead: def func(x): for i in range(x): yield i**2 print(",".join(list(str(func(3))))) #outputs <,g,e,n,e,r,a,t,o,r, ,o,b,j,e,c,t, ,f,u,n,c, ,a,t, ,0,x,7,f,f,4,6,a,6,4,f,3,5,0,> Why did this happen? How can I simply get 0,1,4 or [0,1,4] or ["0", "1", "4"] as intended?

11th Sep 2020, 8:28 PM
Solus
Solus - avatar
2 Answers
+ 3
yield str(i**2)
11th Sep 2020, 8:43 PM
Oma Falk
Oma Falk - avatar
+ 3
func() function returns a generator which must be called to print out it's returned value, try adding an extra parenthesis just after initializing the function inside the print statement (func(3)()) another problem is when you tried to convert the function to a string, using str(… ) be informed that this won't convert each items to a string, instead you're calling the dunder __str__ and I don't think, this is what you're trying to do. So to convert each items to string, try using the map function [*map(lambda s:str(s), [*func(3)]]
11th Sep 2020, 8:40 PM
Mirielle
Mirielle - avatar