Home > Software design >  how can i remove all commas at the end of the string?
how can i remove all commas at the end of the string?

Time:06-30

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

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

CodePudding user response:

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 lst in l for x in lst]

CodePudding user response:

Try this because you have a nested list:

>>> [[b.rstrip(', ') for b in a] for a in l]

[['kjkng,rkggg', 'aaaa', 'sssssss'], ['rjfjrejn lelkkd'], ['fffff']]

CodePudding user response:

res = []
for elist in l:
   ires = []
   for elm in elist:
       ires.append(elm.replace(',','')
   res.append(ires)
          

CodePudding user response:

this will do it.

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

text = [[new_value.rstrip(' , ') for new_value in j] for j in text]

print(text

[['kjkng,rkggg', 'aaaa', 'sssssss'], ['rjfjrejn lelkkd'], ['fffff']]

CodePudding user response:

import re

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

regex = re.compile(r"[, ]*$", re.IGNORECASE)
res = []
for arr in l:
    res.append([])
    for s in arr:
        res[-1].append(regex.sub('',s))
  • Related