Home > Software design >  python - how to use the join method and sort method
python - how to use the join method and sort method

Time:10-26

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

CodePudding user response:

set() 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']

CodePudding user response:

You could use:

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

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