1

I am trying to make/get a new string which doesn't contain spaces. For example,

string1 = "my music is good"

should become

joinedstring = "mymusicisgood"   #this is the one i want

At first i was able to do this by using the built in string method

string1 = "my music is good"
joinedstring = string1.replace(" ","")

But now I am trying to achieve the same results without any string method, which means I have to make my own function. My thought was to make a loop which searches for the index of the "space" in a string then try to delete indexes to make a new string. But here comes the problem, strings are immutable so deleting say del string[index] doesn't work. Any help please!

0

4 Answers 4

2

You don't need to import string to make a replacement. replace() is a method on any string:

>>> string1 = "my music is good"
>>> joinedstring = string1.replace(" ","")
>>> joinedstring
'mymusicisgood'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You, have like a month programming now guess i have to open my book again for that.
0

Alternative solution is to use list comprehension with filter (the if part):

>>> string1 = "my music is good"
>>> "".join([c for c in string1 if c != " "])
"mymusicisgood"

Comments

0

here is a working function that you can call from your code:

def remove_space(old_string):
    new_string = ""
    for letter in old_string:
        if not letter == " ":
            new_string += letter
    print new_string # put here return instead of print if you want

if __name__ == '__main__':
    remove_space("there was a time")

Comments

0

Looks a lot like school homework if you need to "program" built-in functions on your own. A very simple function for that could look like this:

def no_spaces(string1):
    helpstring = ""
    for a in string1:
        if a == " ":
            pass
        else:
            helpstring = helpstring + a
    return helpstring

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.