how to remove seperator from the end of a list python

1.9k views Asked by At

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
4

There are 4 answers

2
joeforker On BEST ANSWER

Just use the join() method:

def to_string(my_list, sep=' '):
    return "List is: " + sep.join(map(str, my_list))

If you would like to use the range() function:

for i in range(len(my_list)):
    if i > 0:
        new_str += sep
    new_str += str(my_list[i])

This is unfortunately horribly un-Pythonic, and inefficient because Python has to copy into a new string for each + concatenation.

7
Namit Singal On

Just return till array_length-len(sep), it should work

import StringIO

def to_string(my_list, sep=' '):
    new_str = StringIO.StringIO()
    new_str.write("List is: ")

    for k in my_list:
        new_str.write(str(k)+sep)
    result = new_str.getvalue()
    new_str.close()
    return result[:-len(sep)]

my_list = [1,2,3,4,5]
string = to_string(my_list, sep='-')
print(string)

@Martjin peters thanks :)

1
Deacon On

Using the join() method is your best solution, but if you truly want to do it yourself, change your return to the following:

return new_str[:-len(sep)]

This will return a string consisting of the string you built except for the last character.

Update

Thanks to Martijn Peters for pointing out that my original didn't deal correctly with separators of len > 1.

2
DuniC On

There are many ways!
If you want to print you could use the print function:

myList = [1,2,3,4,5]
print(*myList, sep=',')          #1,2,3,4,5         #or
print(*myList, sep=',', end=';') #1,2,3,4,5;        #if you like diferent ending...

* makes myList work as five separated arguments not as one list.

If you want a string you could use str.join

myList = [1,2,3,4,5]
sep = ','
myString = sep.join(str(i) for i in myList) #The args need to be str
print(myString)  #1,2,3,4,5

But if you like it the hard way you have to change a little bit your function so it looks like:

def to_string(my_list, sep=' '):
    new_str=str(my_list[0])
    for i in my_list[1:]: #Skip my_list[0]
        new_str += sep + str(i)
    return new_str
myList = [1,2,3,4,5]
print(to_string(myList, ',')) #1,2,3,4,5

[Edit] Answering to @rks of course it is possible to use ranges:

for i in range(1, len(my_list)): #Skip my_list[0]
    new_str += sep + str(my_list[i])