试图让python返回字符串只包含字母和空格
string = input("Enter a string: ")
if all(x.isalpha() and x.isspace() for x in string):
print("Only alphabetical letters and spaces: yes")
else:
print("Only alphabetical letters and spaces: no")
我一直在尝试please
,结果是Only alphabetical letters and spaces: no
我用了or
而不是and
,但这只满足一个条件。我需要两个条件都满足。也就是说,句子必须只包含字母和空格但必须至少包含每种类型中的一个。它必须不包含任何数字。
在这里,python返回的字母和空格只包含在字符串中缺少什么?
正确的解决方案将使用
or
。虽然有一个字符串,但您正在对该字符串的字母进行迭代,因此一次只能有一个字母。因此,一个char本身不能是一个字母字符和一个空格,但它只需要是这两个字符中的一个就可以满足您的约束。
编辑:我在另一个答案中看到了您的评论。
alphabet = string.isalpha()
返回True
,如果且仅当字符串中的所有字符都是字母。这不是您想要的,因为您声明希望您的代码在使用具有空格的字符串please
执行时打印yes
。你需要自己检查每个字母,而不是整个字符串。只是为了让您相信代码确实是正确的(好吧,好吧,您需要自己执行它才能让您信服,但是无论如何):
编辑2:根据您的新评论判断,您需要以下内容:
或者
字符不能同时是alpha和空间。它可以是alpha或空间。
要求字符串只包含字母和空格:
要要求字符串至少包含一个alpha和至少一个空格,请执行以下操作:
要要求字符串至少包含一个alpha,至少包含一个空格,并且仅包含alpha和空格,请执行以下操作:
测试:
实际上,这是一个模式匹配练习,为什么不使用模式匹配呢?
或者在解决方案中使用
any()
有什么要求吗?相关问题 更多 >
编程相关推荐