Problem: Write a function that joins an arbitrary number of string arguments with a given separator.
Example: Given the string arguments "A"
, "B"
, and "C"
and the string separator "-"
. Join them to the concatenated string "A-B-C"
.
Solution: The following code creates a Python function concat()
that takes an arbitrary number of arguments, packs them into the tuple args
using the single asterisk operator, and joins the string arguments in args
using the separator given as the final function argument.
def concat(*args, sep="/"): return sep.join(args) print(concat("hello", "world" sep=" ")) # hello world
Explanation: String concatenation is the process of creating a string by appending string arguments. The given function takes an arbitrary number of string arguments as specified by the *args
keyword. The parameter sep
declares the separator string to clue together two strings. The separator argument is a keyword argument because of the *args
argument can have an arbitrary number of arguments. The keyword argument helps to differentiate whether the last parameter is part of *args
or the sep
argument.
The function concat
is a wrapper for the join
function to concatenate strings. The join
function is defined in the string object sep
. It concatenates an arbitrary number of strings using the separator to glue them together. Both functions achieve the same thing, but the first may be more convenient because the separator is a normal argument.
Yet, you will find yourself using the join
function on a regular basis without writing your own wrapper functions. So you can as well learn its proper use now.
Boost your Python skills—with our cheat-sheet-based Python email academy for continuous improvement of your programming skills. Join thousands of ambitious coders:
Puzzle: What is the output of this code snippet?
Are you a master coder? Test your skills now!
Related Video: Splitting and joining strings in Python

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.