I’m having problems with a homework question.
“Write a function, to_str(a), that takes an array, a, converts each of
its elements to a string (using str(a[i])) and appends all these
strings together.”
This is what I have
def to_str(a):
for i in a: a.append([i])
return str(a[i])
I have no idea how to use str(a[i]), I was wondering if someone can point me to the right direction
From the docs:
So
str(a[i])will return a string representation ofa[i], i.e. converta[i]to a string.You will then need to concatenates the strings for all values of
i.As for your code, I have the following comments:
iis an element ofa, not an index, as you might be thinking;atoa(endlessly, I’m afraid);a[i]can cause an exception, because, like I said,iis an element, not an index;Also, if using
str(a[i])is not strictly mandatory, I’d suggest to skip it as unpythonic. You don’t need indexes at all for this. Examples:or
will return what you need. In both cases
stris applied to all elements ofa.The simplest-to-understand (“beginner”) way without using indexes will be
It’s a bit less efficient, though it does effectively the same thing.