pythonstringif-statement

Can't wrap my head around how to remove a list of characters from another list


I've been able to isolate the list (or string) of characters I want excluded from a user entered string. But I don't see how to then remove all these unwanted characters. After I do this, I think I can try joining the user string so it all becomes one alphabet input like the instructions say.

Instructions:

Remove all non-alpha characters Write a program that removes all non-alpha characters from the given input.

For example, if the input is:
-Hello, 1 world$!
the output should be:
Helloworld

My code:

userEntered = input()
makeList = userEntered.split()
def split(userEntered):
    return list(userEntered)
    
    
if userEntered.isalnum() == False:
    for i in userEntered:
        if i.isalpha() == False:
            #answer = userEntered[slice(userEntered.index(i))]
           reference = split(userEntered)
           excludeThis = i
           print(excludeThis)
 
    

When I print excludeThis, I get this as my output:

-
,
 
1
 
$
!

So I think I might be on the right track. I need to figure it out how to get these characters out of the user input. Any help is appreciated.


Solution

  • Loop over the input string. If the character is alphabetic, add it to the result string.

    userEntered = input()
    result = ''
    for char in userEntered:
        if char.isalpha():
            result += char
    print(result)
    

    This can also be done with a regular expression:

    import re
    
    userEntered = input()
    result = re.sub(r'[^a-z]', '', userEntered, flags=re.I)
    

    The regexp [^a-z] matches anything except an alphabetic character. The re.I flag makes it case-insensitive. These are all replaced with an empty string, which removes them.