1
votes

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(':')
1
That is how you do it, but char[i].strip(':') creates a new string object.jonrsharpe
@jonrsharpe Is there a way I can write that string object back into my list? Also, what happens to the string object I've created. Thanks for your reply!MatrixCitizen01
"In-place": char[:] = [ch.rstrip(':') for ch in char]. See How to modify list entries during for loop?martineau

1 Answers

-1
votes

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]