Skip to content
Advertisement

iterate through a tuple to form a string

I am trying to create a function named make_string, that uses * correctly with a parameter: strings The function should return a string of all the values supplied joined, and separated by a space. Outside the make_string function, I declare a variable named my_string, and assign the value returned from the make_string function. Then I call the make_string function with the following values: “Alderaan”, “Coruscant”, “Dagobah”, “Endor”, “Hoth”. Finally I print the value of my_string to the terminal…and it returns None, when it should return Alderaan Coruscant Dagobah Endor Hoth Can anybody tell me where I am going wrong please?

def make_string(*strings):
    my_string = ""
    for x in strings:
        my_string = x.join(strings)
        return my_string

my_string = make_string()

make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")

print(my_string)

Advertisement

Answer

There are a few things going on in your code that are a little wonky.

  1. You’re constantly re-assigning the value of my_string every time you loop through for x in strings
  2. There’s no reason to start with a blank string here since you’re already using join
  3. Your function call isn’t setting to my_string — it isn’t set to anything. What you want is like my_string = make_string("Bob", "Mary") etc.

This should do the trick:

def make_string(*strings):
    return " ".join(strings)

my_string = make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")

print(my_string)

Personally, I would say you don’t even need a function here, especially if you can easily set what you’re using for *strings to a variable. For example:

planets = ["Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth"]
print(" ".join(planets))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement