简体   繁体   中英

python: how to sort a string alphabetically and by len

shakespeare = 'All the world is a stage, and all the men and women merely players. They have their exits and their entrances, And one man in his time plays many parts.'

Create a function that returns a string with all the words of the sentence shakespeare ordered alphabetically. Eliminate punctuation marks.

(Tip: the three first words should be ' a all all', this time duplicates are allowed and remember that there are words in mayus)

def sort_string(shakespeare):
    return string_sorted

Here you get a one-liner

import re

shakespeare = "All the world is a stage, and all the men and women merely players. They have their exits and their entrances, And one man in his time plays many parts."

print (sorted(re.sub(r"[^\w\s]","",shakespeare.lower()).split(), key=lambda x: (x,-len(x))))

Output:

['a', 'all', 'all', 'and', 'and', 'and', 'and', 'entrances', 'exits', 'have', 'his', 'in', 'is', 'man', 'many', 'men', 'merely', 'one', 'parts', 'players', 'plays', 'stage', 'the', 'the', 'their', 'their', 'they', 'time', 'women', 'world']

The corresponding function:

def sort_string(shakespeare)
    return sorted(re.sub(r"[^\w\s]","",shakespeare.lower()).split(), key=lambda x: (x,-len(x)))

In case you want a string to be returned:

def sort_string(shakespeare)
    return " ".join(sorted(re.sub(r"[^\w\s]","",shakespeare.lower()).split(), key=lambda x: (x,-len(x))))

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