Reputation:
Am trying to implement a concatenation of strings in python, these strings are passed into the function as multiple parameters via a tuple...I just quite can't figure out how to process multiple string parameters and use join
method to put a -
delimiter between the strings. For example when i pass values I
, Love
,Python
, am expecting to see I-Love-Python
..
Check out below
##Define a function that takes multiple string arguments
def concatenate(*args):
#Got a problem processing the tuple elements and append delimiter - to the end of each word
#Tried using a set with its add method but it didn't work
u=len(args)#Get the length of the arguments tuple
myarray={0}#initialize a new set to length 0
for k in range(0, u):
myarray.add(args[k]+"-")#append delimiter for every tuple member
return myarray
##call concatenate with parameters and print
print(concatenate("I","Love","Python"))
Upvotes: 1
Views: 5193
Reputation: 34431
As noted in the comments section above, you can simply use Python's built-in string function, i.e., .join()
, to concatenate multiple string parameters separated by a delimiter (in this case, that is -
). Example:
s = '-'.join(['I','Love','Python'])
print(s) # I-Love-Python
Note: if you have non-string attributes, you have to convert those to strings first. For example:
points = 3
s = '-'.join(['Each','player', 'has', str(points),'points'])
print(s) # Each-player-has-3-points
If you had to do this through a function that expects a number of arguments, for instance def concatenate(*args)
, then simply use '-'.join(args)
. Again, remember to convert any non-string arguments first, or use the below to automatically convert any non-string arguments to string, before concatenating them.
def concatenate(*args):
return "-".join(map(str, list(args)))
print(concatenate('Each', 'player', 'has', 3, 'points')) # Each-player-has-3-points
Upvotes: -1
Reputation: 87
Change your code as shown below:
##Define a function that takes multiple string arguments
def concatenate(*args):
return "-".join(args)
##call concatenate with parameters and print
print(concatenate("I","Love","Python"))
OUTPUT:
'I-Love-Python'
Upvotes: 1