用于按字母顺序对单词排序的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


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

源代码

# 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() 方法对单词列表进行排序,并显示所有单词。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战