IndusWarrior IndusWarrior - 1 month ago 13
Python Question

Does String operation like below uses extra space in python?

If I use the following code to remove spaces from the string S, will it be considered as using extra space/memory? Given 'S' string of 'l' length .

int n = l
while i < n
if S[i] == " ":
S = S[0:i] + S[i+1:]
n = len(S)
print "the new string ", S

Edit: This is just a sample code. Please don't comment about its complexity and/or correct way of removing spaces :). The context here was, while solving an algorithm design question, involving some string operation, there was a restriction of using extra space. And I wanted to know operation like this are using extra memory/space or not.


Every time you do something like a[b:c] python creates a new object. So yes you are using extra space. I would suggest using replace() method like so:

S.replace(" ", "")

It will delete all spaces in one go.

And btw, you don't increment i in your code and : is missing in while statement.