+ 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
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))
...
+ 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", "!")
+ 4
def concatenate(*args):
print('-'.join(args))
concatenate("I", "love", "Python", "!")
OR
def concatenate(*args):
print(*args, sep='-')
concatenate("I", "love", "Python", "!")
+ 3
Thanks all.
+ 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", "!")