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 ...")
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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!
Excellent! If you already have some char and not a collection, you may be able to replace 'em directly with .replace() or a regex, or speculating, perhaps you're really looking for URL encoding docs.python.org/3/library/… (which will handle special characters too)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.