0

I need to remove extra spaces in string. And I need to use O(1) memory. Is it possible to not use lists, because lists use more memory than strings (I've checked it with sys.getsizeof()) or when I use split() I'm still using O(1) memory?

There is code

s = input()
s = s.split('_')
s = list(filter(lambda a: a != '', s))
print('_'.join(s))

1 Answers1

1

I would usually do this to remove extra spaces

text = ' '.join(text.split()).strip()

Though if you don't want to use list you can use regex

import re
text = re.sub(r' {2,}', ' ', text).strip()
Ron Serruya
  • 3,988
  • 1
  • 16
  • 26