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?
charin yourforloop is just a copy of the character instring. So, settingchar = tempwill only change the variablecharto have the value"", not remove the space.print()adds a newline on every loop. I've closed your question as a duplicate accordingly. However, printing is not the same as returning, so you'll need to find a new approach. Now, please read the homework questions FAQ. The way this question is written, you're asking us to do your homework for you, which is not what we're about. Instead, to make this a constructive question for SO, you'd want to focus on your own approach. See also How to Ask in general.