Search code examples
pythoninputreplacenumbers

Removing all numbers form an input in Python


Is there a way to remove all numbers in Python? like so: user input: Lorem Ipsum 78432 Lorem Ipsum

Output: Lorem Ipsum Lorem Ipsum

I've tries looking it up, its only about removing spaces, I've also tried using .replace('X', '')


Solution

  • You can make a list with all the characters you want to remove to the sentence, then loop through each character in the user input, and see whether its in the list of characters you want to remove. If it is not on the list, we'll add it to a list with all the characters that we want to keep. And if the character is in the list, we'll ignore it. Like so:

    #Make a function called clean_input, which takes 1 argument - the sentence that you want to clean
    def clean_input(input):
        #make sure input is a string, in case it was only numbers
        str(input)
    
        #make a list of all the characters you want to remove from the sentence
        undesired_characters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        #make a list to contain the characters that aren't in the list of undesired characters
        desired_characters = []
    
        #loop through every character in the sentence
        for character in input:
            #if the letter isn't in the list of undesired characters
            if character not in undesired_characters:
                #append it to the list of desired characters
                desired_characters.append(character)
            #if the character is in the list of undesired characters
            elif character in undesired_characters:
                #skip it, go to the next character
                pass
    
        #join the characters in the list into a string, with nothing being added between
        cleaned_input = "".join(desired_characters)
    
        #remove any double spaces ('  ')
        cleaned_input = cleaned_input.replace("  ", " ")
    
        #return the cleaned up input
        return cleaned_input
    
    #clean a sentence using our function, and print it
    new_input = clean_input("Lorem Ipsum 78432 Lorem Ipsum")
    print (new_input)
    

    The output will be:

    Lorem Ipsum Lorem Ipsum
    

    PS - We need to remove double spaces because if you have hello 4 hello and you remove 4, you'll be left with hello hello. So after removing all numbers, we check for the double spaces and replace it with a single space.