Replacing spaces in a string

Q. Write a method to replace all spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the “true” length of the string.

EXAMPLE
Input: “Mr John Smith ”
Output: “Mr%20John%20Smith”

def replace_spaces(str1):
    
    space_count = 0
    
    for char in str1:
        if char == " ":
            space_count += 1
            
    new_length = len(str1) + 2*space_count
    str_list = [""]*new_length
    
    for i in range(len(str1)-1,-1,-1):
        if str1[i] == " ":
            str_list[new_length-1] = "0"
            str_list[new_length-2] = "2"
            str_list[new_length-3] = "%"
            new_length -= 3
        else:
            str_list[new_length-1] = str1[i]
            new_length -= 1
            
    return "".join(str_list)

if __name__ == "__main__":
    print replace_spaces("my name is debanjan mahata")
    assert replace_spaces("my name is debanjan mahata") == "my name is debanjan mahata".replace(" ","%20")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s