How to make a function that concatenetes strings in python

I'm taking the codeacademy course and it asks me the following:

Define a function called join_strings accepts an argument called words. It will be a list. Inside the function, create a variable called result and set it to "", an empty string. Iterate through the words list and append each word to result. Finally, return the result. Don't add spaces between the joined strings!

So what I did is:

def join_strings(words):
    result = ""
    for i in range(len(words)):
        result = words
    return result

But the console prints me:

Oops, try again. join_strings(['x', 'y', 'z', 'a']) returned ['x', 'y', 'z', 'a'] instead of 'xyza'

Upvotes: 0

Views: 673

Answers (4)

Aj-G
Aj-G

Reputation: 1

The following has worked for me:

n = ["Michael", "Lieberman"]

Add your function here

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

print join_strings(n)

Upvotes: -1

Dinesh Panchananam
Dinesh Panchananam

Reputation: 694

Try the following code:

from operator import add
def join_strings(words):
    return reduce(add, words)

Upvotes: 0

Abe Malla
Abe Malla

Reputation: 67

Try this one:

def join_strings (words):
    result = ""
    for i in words:
        result += i
    return result

Basically, we have an empty string. We can add more to this string by using the += operator. This operator is short for saying x = x + y.

Upvotes: 1

backtrack
backtrack

Reputation: 8144

def join_strings(words):
    result = ""
    for i in words:
        result += i
    return result

you have missed this result += words concatenation part and return result

you have to use this

for i in words:
            result += i

Update

def join_strings(words):
    result = ""
    for i in words:
        result += i
    return result

g= join_strings(['x', 'y', 'z', 'a'])

print(g)

o/p : xyza

From your post :

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

g= join_strings(['x', 'y', 'z', 'a'])

print(g)

You have to use the index value of the word. Since you are getting the range and iterating you have to specify the index result += words[i]

Upvotes: 2

Related Questions