python string remove without using internal function

Question:

I’m a freshman CS student. This is one of the exercises we had in class:

Create a function called remove_space(string):

  • The function takes in a string as input
  • The function returns a new string, which is generated by removing all the spaces in the given string.
  • Example: remove_space(“welcome to computer science”) returns “welcometocomputerscience”

I have looked around for solutions online but we aren’t allowed to use any advanced functions like split(), replace(), join() or anything of that sort. I’m looking for the most primitive way to solve this without using those that would make sense coming from a freshman CS student.

This is what I have so far:

def remove_space(string):                                                             
    temp = ""                                                                             
    for char in string:                                              
        if char == " ":                                            
           char = temp                                      
        print(char)

print("----------------#1---------------")                              
remove_space("Welcome to computer science")

What am I doing wrong?

Asked By: Dibbi Barua

||

Answers:

def remove_space(string):                                                             
    result_string = ''                                                                             
    for character in string:                                              
        if character != ' ':                                            
           result_string += character
    return result_string

remove_space('welcome to computer science')

Result:

'welcometocomputerscience'
Answered By: Barry the Platipus

Try this:
Create a variable temp, concat the char if it is != " " and then return temp

def remove_space(string):
    temp = ""
    for char in string:
        if char != " ":
            temp += char
    return temp
print(remove_space("welcome to computer science"))
Answered By: Felix Jäger

Simple answer:
When you write char = temp, you are basically assigning the variable to a new value instead of overriding t in the original string.

What you are doing is equivalent to:

a = 3
b = a
b = 2

Even though you tell b to be equal a, you reassign it later to be 2. If you print(a) you will see that its value will still be the same.

CS-Dojo has a great video on this https://youtu.be/Z1Yd7upQsXY?t=1002 you can start at minute 16 where he explains variable assignment.

Answered By: Mohamad Kamar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.