Stuck on 'Using Strings in Lists in Functions', please help!


#1



Using strings in lists in functions

Traceback (most recent call last):
File "python", line 11, in
File "python", line 7, in join_strings
AttributeError: 'str' object has no attribute 'append'


n = ["Michael", "Lieberman"]
# Add your function here

def join_strings(words):
    result = ""
    for i in range(len(words)):
        result.append(words[i])
    return result 


print join_strings(n)


#2

append() is a built in function which appends items to a list, use + to join strings


#3

Create a function that concatenates strings.

1.Define a function called join_strings accepts an argument called words. It will be a list.
2.Inside the function, create a variable called result and set it to "", an empty string.
3.Iterate through the words list and append each word to result.
4.Finally, return the result.

Don't add spaces between the joined strings!

Those are the instructions. So what does it mean when it says 'append each word to result'?


#4

it says append, i get that, but append() which you use here:

result.append(words[i])

is designed to work for lists, not for strings. to append strings you need to use +:

example1 = "hello"
example2 = "world"
print example1 + example2 # will print helloworld

#5

Ok I understand now this worked for me:

result += words[i]

I also want to ask why do you write += and not just +.
when i wrote just + it didnt work for me.


#6

well, i just wanted to show how joining strings was done, i was trying to push you in the right direction, giving the answer will have taught you very little.


#7

but why do you have to write += and not just +?


#8

also what is the looping variable?


#9

because just writing plus will not update the variable? += will

look:

example = 10
print example # will print 10
print example + 5 # will print 15
print example # will print 10
example += 5
print example # will print 15

+= will update the variable, it is actually a shorthand, you could also write:

example = example + 5

with other words: update example with what is already stored in example and add 5


#10

Ok i understand now, Thank you very much. I'd also like to know what it means when it says 'Iterate through lists. Call the looping variable numbers.'
what is the looping variable?


#11

in this code:

for i in range(len(words)):

i would be the looping variable (the variable which gets assigned the values)


#12

Ok, Thank you very much :smile: you have been a huge help.


#13