How can I remove the last separator from the end of a list?
Here's a function I created to place any separator between elements of a list.
def to_string(my_list, sep=' '):
new_str = "List is: "
index = 0
for k in my_list:
new_str = new_str + str(k) + sep
return new_str
my_list = [1,2,3,4,5]
string = to_string(my_list, sep='-')
print(string)
Current output:
List is: 1-2-3-4-5-
What I want it to be:
List is: 1-2-3-4-5
Just use the
join()
method:If you would like to use the range() function:
This is unfortunately horribly un-Pythonic, and inefficient because Python has to copy into a new string for each
+
concatenation.