Skip to main content
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Source Link
CodeYogi
  • 5.2k
  • 12
  • 52
  • 106

Replace spaces in string

import re


def replace_token_regex(s, token=" "):
    return re.sub(token, '20%', s.strip())
    
def replace_token_inplace(s, token=" "):
    
    for index, char in enumerate(s):
        if ord(char) == ord(token):
            s[index] = '20%'
    return s
    
print replace_spaces_regex("Foo Bar ")
s = list("Foo Bar ")
replace_spaces_inplace(s)
print ''.join(s)

The run time complexity of the above code is \$O(n)\$, can it be further optimized? or is there any better way to do the above computation?