-1

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(':')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    That *is* how you do it, but `char[i].strip(':')` creates a **new** string object. – jonrsharpe Dec 17 '20 at 20:55
  • @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 Dec 17 '20 at 20:58
  • "In-place": `char[:] = [ch.rstrip(':') for ch in char]`. See [How to modify list entries during for loop?](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) – martineau Dec 17 '20 at 21:01

1 Answers1

-1

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]
crackaf
  • 492
  • 2
  • 11