Python代码 在线执行

Python 程序:按字母顺序对单词进行排序

/examples/alphabetical-order

在此程序中,您将学习使用for循环按字母顺序对单词进行排序并显示它。

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


在此示例中,我们说明了如何按字典顺序(字母顺序)对单词进行排序。

源代码

# 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 = 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:
Example
Hello
Is
With
an
cased
letters
this

注意:要测试程序,请更改my_str的值。

在此程序中,我们将要排序的字符串存储在my_str中。 使用split()方法将字符串转换为单词列表。 split()方法将字符串分割为空白。

然后使用sort()方法对单词列表进行排序,并显示所有单词。