Program Python pentru sortarea cuvintelor în ordine alfabetică

Cuprins

În acest program, veți învăța să sortați cuvintele în ordine alfabetică folosind for loop și să le afișați.

Pentru a înțelege acest exemplu, ar trebui să aveți cunoștințele următoarelor subiecte de programare Python:

  • Python pentru buclă
  • Șiruri Python
  • Metode String

În acest exemplu, ilustrăm modul în care cuvintele pot fi sortate lexicografic (ordine alfabetică).

Cod sursa

 # 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) 

Ieșire

 Cuvintele sortate sunt: ​​un exemplu de caz hello sunt literele cu care 

Notă: Pentru a testa programul, modificați valoarea my_str.

În acest program, stocăm șirul pentru a fi sortat în my_str. Folosind metoda split () șirul este convertit într-o listă de cuvinte. Metoda split () împarte șirul la spații albe.

Lista cuvintelor este apoi sortată folosind metoda sort () și sunt afișate toate cuvintele.

Articole interesante...