Selles programmis õpite sõnu tähestiku järjekorras loopi jaoks sortima ja seda kuvama.
Selle näite mõistmiseks peaksid teil olema teadmised järgmistest Pythoni programmeerimise teemadest:
- Python for Loop
- Pythoni stringid
- Stringimeetodid
Selles näites illustreerime, kuidas sõnu saab leksikograafiliselt (tähestikulises järjekorras) sorteerida.
Lähtekood
# Program to sort alphabetically the words form a string provided by the user my_str = "Hello this Is an Example With cased letters" # To take input from the user #my_str = input("Enter a string: ") # breakdown the string into a list of words words = (word.lower() for word in my_str.split()) # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word)
Väljund
Sorteeritud sõnad on: tere tähistatud näide tähistab seda
Märkus. Programmi testimiseks muutke my_str väärtust.
Selles programmis salvestame sorteeritava stringi my_str. Split () meetodi abil teisendatakse string sõnade loendiks. Split () meetod jagab stringi tühikutel.
Seejärel sorteeritakse sõnade loend sort () meetodi abil ja kuvatakse kõik sõnad.