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'],[], .....]]
>Solution :
let’s look around the cases:
- 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]
- 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]