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