python - how to use the join method and sort method

Viewed 137

My purpose is to get an input as a string and return a list of lower case letters of that string, without repeats, without punctuations, in alphabetical order. For example, the input "happy!" would get ['a','h','p','y']. I try to use the join function to get rid of my punctuations but somehow it doesn't work. Does anybody know why? Also, can sort.() sort alphabets? Am I using it in the right way? Thanks!

def split(a):
    a.lower()
    return [char for char in a]

def f(a):
    i=split(a)
    s=set(i)
    l=list(s)
    v=l.join(u for u in l if u not in ("?", ".", ";", ":", "!"))
    v.sort()
    return v
3 Answers

.join() is a string method, but being used on a list, so the code raises an exception, but join and isn't really needed here.

You're on the right track with set(). It only stores unique items, so create a set of your input and compute the intersection(&) with lower case letters. Sort the result:

>>> import string
>>> s = 'Happy!'
>>> sorted(set(s.lower()) & set(string.ascii_lowercase))
['a', 'h', 'p', 'y']

You could use:

def f(a):
    return sorted(set(a.lower().strip('?.;:!')))

>>> f('Happy!')
['a', 'h', 'p', 'y']

You could also use regex for this:

pattern = re.compile(r'[^a-z]')

string = 'Hello@ W0rld!!#@'

print(sorted(set(pattern.sub('', string))))

Output:

['d', 'e', 'l', 'o', 'r']
Related