Search code examples
pythonliststrip

Is there a way to rstrip the same character from every item in a list?


I'm trying to strip a colon (':') from every string in a list of 1000 strings. So far, I've tried using a map function with a rstrip and just a strip function but have had no luck. I also tried a simpler for loop function as seen below.

I'm not getting any errors, but when I try to print char it doesn't remove the colons

char = ['g:', 'l:', 'q:'] #in my actual code there are 1000 strings

for i in range(0,999):
  char[i].strip(':')

and also

for i in range(0,999):
   char[i].rstrip(':')

Solution

  • str.strip() return a new str object. It doesn't change the original. So the loop should be something like this.

    for i in range(0,999):
      char[i]=char[i].strip(':')
    

    Or better use list comprehension

    char=[x.strip(':') for x in char]