Adding Spaces Between Concatenated Words


#1

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,

MD


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

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] + " "
  else:
    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!