如何检查一个字符串是否包含 python 中字母表的所有字母?

新手上路,请多包涵

我正在尝试编写一个 python 程序来检查给定的字符串是否是 pangram - 包含字母表中的所有字母。

因此, "We promptly judged antique ivory buckles for the next prize" 应该返回 True 而任何不包含字母表中的每个字母至少一次的字符串应该返回 False

我相信我应该为此使用 RegEx,但我不确定如何使用。它看起来应该类似于:

 import sys
import re

input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]

if (re.search('string contains every letter of the alphabet',input_string):
    return True
else:
    return False

原文由 Maslor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 388
2 个回答

这不是我用正则表达式解决的问题,不。创建一组小写字符串并检查它是否是字母表中字母的超集:

 import string

alphabet = set(string.ascii_lowercase)

def ispangram(input_string):
    return set(input_string.lower()) >= alphabet

只有当字母表中的 每个 字母都在从输入文本创建的集合中时,它才是超集;通过使用超集而不是相等,除了 (ASCII) 字母之外,您还允许使用标点符号、数字和空格。

演示:

 >>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我在 python 中的解决方案:

 alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input()
sentence = sentence.lower()
missing = ''
for letter in alphabet:
  if letter not in sentence:
    missing = missing+letter
if (len(missing) != 0):
  print("missing", missing)
else:
  print("pangram")

原文由 jeonbik 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题