n = ["Michael", "Lieberman"]
def join_strings(words):
result=""
for i in range(len(words)):
result=result.append(words[i])
return result
print join_strings(n)
got error: error: AttributeError: ‘str’ object has no attribute ‘append’
And when I saw the solution I realized that append works on lists and not strings! I was stuck yesterday because the wording of the exercise confused me that I should use the append function! Just a reminder that append doesnt work with str, seems like. Also important to note is that if ur using the simpler method of for i in words: - you can use both result+=i and result+=words[i] but if ur using the more complicated range one you should always use result+=words[i]. Im just curious why it cant work without me pointing out that i is an index in words list? Some help?
This is the good things, there are multiply ways to solve the problem. If you want to append to a string you can use +=, but you can also use .join, but then you would have to use it correctly:
n = ["Michael", "Lieberman"]
def join_strings(words):
result = "".join(words)
return result
print join_strings(n)
Your join simple contains too many flaws. where you have result, that should be what should be used to join "" simply means nothing, "-" would have given Michael-Lieberman, and you can call join directly on a list, no need to loop it
Follow-up question: Is there a way to use append in this context? If not, can you please explain specifically why it wouldn’t work (and maybe where it would be applicable)?_
you could concat/join the string together:But not with append, because the .append() function is only for lists.
you would get something like this:
n = ["Michael", "Lieberman"]
def join_strings(words):
x = ""
for i in words:
x += i
return x
print join_strings(n)
you just join the string with +, just like you would do to join/concat a string for printing, except this time you store it in a variable. This is nothing new, right?
@stetim94 i tried what you wrote but my error message says “Oops, try again. string_function(‘Hello’) returned ‘H’ instead of ‘Helloworld’” In my output box it says “MichaelLieberman None”
if you used result += words[i] it will join them to the the string without any spaces or flaws
but “”.join(words) will join them with flaws and you can add any flaws you want