简体   繁体   中英

python - how to use the join method and sort method

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

.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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM