Reputation: 29
So I'm supposed to create a function that takes any sort of iterable input and converts it into a string of that input separated by spaces. For example, if you were to call iteration_to_string("abcd") it would return "a b c d " (the space at the end is allowed). or if [1, 2, 3, 4] is the input, it should return "1 2 3 4 ". All I have so far is how to turn the input into a set and Im confused where to go to turn it into a string. I assume it would be adding something into the for loop that would somehow concatenate the inputs together with a space but Im not sure how to do that. Any help is appreciated!
def iteration_to_string (data):
new = set()
for i in range (len(data)):
new.add(data[i])
return " ".join(new)
Upvotes: 0
Views: 578
Reputation: 46901
for any iterable
' '.join(iterable)
will return a string with all the elements in iterable separated by a space. refer to str.join(iterable)
.
if the elements in iterable are not strings you need to
' '.join(str(item) for item in iterable)
(you can do this with any other string as well; ''.join(iterable)
if you do not want any spaces in between).
Upvotes: 1
Reputation: 19753
your code might not work for list containing element int like [1,2,3,4] because join takes string
so you can convert them to int before join like this:
>>> def my_join(x):
... return " ".join(map(str, x))
...
>>> my_join([1, 2, 3, 4])
'1 2 3 4'
you can use list comprehension, if you dont want to use map
>>> def my_join(x):
... return " ".join(str(element) for element in x))
>>> my_join(['a', 'b' ,'c', 'd'])
'a b c d'
Upvotes: 1