在本例中,我们演示了如何按字典序(字母顺序)对单词进行排序。
源代码
# 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)
输出
The sorted words are: an cased example hello is letters this with
注意:要测试该程序,请更改 my_str 的值。
在这个程序中,我们将要排序的字符串存储在 my_str 中。使用 split() 方法,字符串被转换成一个单词列表。split() 方法在空白处分割字符串。
然后使用 sort() 方法对单词列表进行排序,并显示所有单词。