Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i remove all commas at the end of the string?

I want to remove all the commas that are in last of every string i tried s.rstrip it work only for the last comma

l = [['kjkng,rkggg,,,,,,,,,,', 'aaaa, , ', 'sssssss, , , '],['rjfjrejn lelkkd ,,,,,'], ['fffff , , ,'],[], .....]]

i want result as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

l = [['kjkng,rkggg', 'aaaa', 'sssssss'],['rjfjrejn lelkkd'],['fffff'],[], .....]]

>Solution :

let’s look around the cases:

  1. List of strings

in this case the simplest solution is to do a list comprehension and use the str.rstrip(", ") to remove commas and spaces at the end of the string.

l = [x.rstrip(", ") for x in l]
  1. Nested List of strings

in this case, illustrated as an example, you can do in a recursive way and a linear way

  • recursive

do a function wich takes a list and returns another list like in the code:

def remcommas(lst:list):
    final = []
    for x in lst:
        if x.isinstance(x,list):
            x = remcommas(x)
        final.append(x)
    return final

this works if your list is nested but it’s not the optimal solution.

  • linear

this will still use str.rstrip() and work with list of list but it has a constrain:

  • this will work on lists with a structure like what you have (list[list[str]])

But it’s probably the best for now that i can think of, uses list comprehension:

final = [x.rstrip(", ") for x in lst for lst in l]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading