+ 1

Adding Words Problem

Hi, here is my code for “adding word” problem: def concatenate(*args): for i in range(len(args)): print(args[i], end="-") concatenate("I", "love", "Python", "!") After running this code, I am getting the output like below: I-love-Python-!- How to remove the last - ? TIA

28th Mar 2022, 5:49 AM
ShineTek
ShineTek - avatar
5 Answers
+ 5
we can use the join() function with '-' as argument. '-'.join(...) creates a string and separates the elements of variable args by a '-' : def concatenate(*args): print('-'.join(args)) ...
28th Mar 2022, 2:30 PM
Lothar
Lothar - avatar
+ 4
Try it this way, using the unpacking operator * to replace the loop and print the list elements without their enclosing brackets. Specify the separator between elements by using sep= instead of end=. def concatenate(*args): print(*args, sep="-") concatenate("I", "love", "Python", "!")
28th Mar 2022, 6:30 AM
Brian
Brian - avatar
+ 4
def concatenate(*args): print('-'.join(args)) concatenate("I", "love", "Python", "!") OR def concatenate(*args): print(*args, sep='-') concatenate("I", "love", "Python", "!")
29th Mar 2022, 7:15 AM
CodeStory
CodeStory - avatar
+ 3
Thanks all.
29th Mar 2022, 3:33 PM
ShineTek
ShineTek - avatar
+ 2
Hi Shine1Tek! You may find the ternary operator useful in this case. You can keep adding the "-" symbol until it meets the last word. Here's how you do it def concatenate(*args): for i in range(len(args)): print(args[i], end="-" if args[i] != args[-1] else "") concatenate("I", "love", "Python", "!")
28th Mar 2022, 6:02 AM
Python Learner
Python Learner - avatar