Adding Spaces Between Concatenated Words


In this activity, the program author is happy to accept MichaelLieberman as the end result. This is fine for an exercise in concatenating strings, but not-so-fine for someone’s name. Assuming Lieberman is Michael’s last name and not an individual. Regardless, the result is odd.

n = ["Michael", "Lieberman"]

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

I made the amendment of adding a string containing a space to the concatenation of the original strings. I felt that this was the best way to add the space between the names without modify the existing strings in the list. But, I may be wrong.

Is there a better way to achieve the same results?

Thank you,


FAQ: Learn Python - Lists and Functions - Using strings in lists in functions

Hi @waxmelly,

That code looks pretty good, but there is a trailing space after the name.

>>> join_strings(n)
'Michael Lieberman '
                # ↑ this

If that bothers you, you could add an if statement to avoid adding a space after the last word:

for w in range(len(words)):
  if not words[w] == words[-1]:
    result += words[w] + " "
    result += words[w]

Also, using this syntax will produce the same output and may be more readable than using range(len(words)) in your loop:

for word in words:
  result += word

Hope this helps!