用于检查两个字符串是否为字谜的 Python 程序

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


如果通过重新排列一个字符串中的字符可以形成另一个字符串,那么这两个字符串就被认为是易位词(anagram)。例如,Race 和 Care。这里,通过重新排列 Care 的字符,我们可以形成 Race。


使用 sorted() 检查两个字符串是否为易位词的 Python 程序

str1 = "Race"
str2 = "Care"

# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()

# check if length is same
if(len(str1) == len(str2)):

    # sort the strings
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)

    # if sorted char arrays are same
    if(sorted_str1 == sorted_str2):
        print(str1 + " and " + str2 + " are anagram.")
    else:
        print(str1 + " and " + str2 + " are not anagram.")

else:
    print(str1 + " and " + str2 + " are not anagram.")

输出

race and care are anagram.

我们首先将字符串转换为小写。这是因为 Python 是大小写敏感的(即,Python 中 `R` 和 `r` 是两个不同的字符)。

这里,

  • lower() - 将字符转换为小写
  • sorted() - 对两个字符串进行排序

如果排序后的数组相等,则字符串是易位词。


另请阅读

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

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

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

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