skysthelimit91
skysthelimit91

Reputation: 179

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:

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 out how to get these characters out of the user input.

Upvotes: 2

Views: 9687

Answers (2)

Acccumulation
Acccumulation

Reputation: 3591

There's basically two main parts to this: distinguish alpha from non-alpha, and get a string with only the former. If isalpha() is satisfactory for the former, then that leaves the latter. My understanding is that the solution that is considered most Pythonic would be to join a comprehension. This would like this:

''.join(char for char in userEntered if char.isalpha())

BTW, there are several places in the code where you are making it more complicated than it needs to be. In Python, you can iterate over strings, so there's no need to convert userEntered to a list. isalnum() checks whether the string is all alphanumeric, so it's rather irrelevant (alphanumeric includes digits). You shouldn't ever compare a boolean to True or False, just use the boolean. So, for instance, if i.isalpha() == False: can be simplified to just if not i.isalpha():.

Upvotes: 1

Barmar
Barmar

Reputation: 781741

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.

Upvotes: 1

Related Questions