原文: https://www.programiz.com/python-programming/examples/alphabetical-order
在此程序中,您将学习使用for循环按字母顺序对单词进行排序并显示它。
要理解此示例,您应该了解以下 Python 编程主题:
在此示例中,我们说明了如何按字典顺序(字母顺序)对单词进行排序。
源代码
# Program to sort alphabetically the words form a string provided by the usermy_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 wordswords = my_str.split()# sort the listwords.sort()# display the sorted wordsprint("The sorted words are:")for word in words:print(word)
输出
The sorted words are:ExampleHelloIsWithancasedlettersthis
注意:要测试程序,请更改my_str的值。
在此程序中,我们将要排序的字符串存储在my_str中。 使用split()方法将字符串转换为单词列表。 split()方法将字符串分割为空白。
然后使用sort()方法“)对单词列表进行排序,并显示所有单词。
