0

It is hard for me to understand that what's going on in the following code. I am actually trying to remove the leading and trailing space from the string in python. The string has two leading and trailing spaces like this

"  Hello World!  "

I tried following simple code to remove the spaces

s = "  Hello World!  "
temp = s.split(" ")
//output of temp -> ['', '', 'hello', 'world!', '', '']
for x in temp:
   if x == "":
     temp.remove(x)
print(temp)
//output of temp  -> ['hello', 'world!', '', '']

So it only removes the leading trailing spaces and not trailing. Can anyone explain why this function skipping the last two spaces? Note: I don't want to use strip function, just curious about what's going on under the hood

martineau
  • 119,623
  • 25
  • 170
  • 301
Ashish Jambhulkar
  • 1,374
  • 2
  • 14
  • 26
  • 3
    I'd recommend against using `remove` in a loop on the same list, as you'll end up skipping items. But you can do a simple `temp = [x for x in temp if x != ""]` – njzk2 Jan 27 '20 at 01:58
  • 1
    If you are curious about what exactly happens, run your code through a step-by-step debugger and look at the values of x and temp at each iteration. that should be interesting – njzk2 Jan 27 '20 at 01:59
  • `temp = [x for x in temp if x ]` will also work since an empty string is falsy. – shanecandoit Jan 27 '20 at 02:17

0 Answers0