2

I'm trying to make a function that takes in an undetermined amount of parameters, which are the words, that will add a "+" between the single words. At the end it should still be a string.

def add_words(word1 word2 word3 ...)

output:

"word1+word2+word3 ...")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Celltox
  • 127
  • 8
  • 1
    https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function and https://stackoverflow.com/questions/33270019/python-3-str-join-with-seperator – Yevhen Kuzmovych Jan 22 '21 at 16:05

1 Answers1

5

You can use the .join() method of strings and argument expansion to do this!

def add_words(*words):
    return "+".join(words)
>>> add_words("foo", "bar", "baz")
'foo+bar+baz'

Note that the .join() method is actually being used from the string "+", rather than the argument words

ti7
  • 16,375
  • 6
  • 40
  • 68
  • It's a bit different from what I wanted to do but still helped me out. I didn't have the words split up in different stings and just had a full sentence so I wrote a function for that and then used your solution. Thanks for helping me! – Celltox Jan 22 '21 at 17:16
  • 1
    Excellent! If you already have some char and not a collection, you may be able to replace 'em directly with [`.replace()` or a regex](https://stackoverflow.com/questions/65801481/how-to-add-suffix-to-a-plain-text-in-python), or speculating, perhaps you're really looking for URL encoding https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode (which will handle special characters too) – ti7 Jan 22 '21 at 17:25