python判断字符是否为空格_检查字符串是否仅为字母和空格-Python

正确的解决方案将使用or。string = input("Enter a string: ")

if all(x.isalpha() or x.isspace() for x in string):

print("Only alphabetical letters and spaces: yes")

else:

print("Only alphabetical letters and spaces: no")

虽然有一个字符串,但您正在对该字符串的字母进行迭代,因此一次只能有一个字母。因此,一个char本身不能是一个字母字符和一个空格,但它只需要是这两个字符中的一个就可以满足您的约束。

编辑:我在另一个答案中看到了您的评论。alphabet = string.isalpha()返回True,如果且仅当字符串中的所有字符都是字母。这不是您想要的,因为您声明希望您的代码在使用具有空格的字符串please执行时打印yes。你需要自己检查每个字母,而不是整个字符串。

只是为了让您相信代码确实是正确的(好吧,好吧,您需要自己执行它才能让您信服,但是无论如何):>>> string = "please "

>>> if all(x.isalpha() or x.isspace() for x in string):

print("Only alphabetical letters and spaces: yes")

else:

print("Only alphabetical letters and spaces: no")

Only alphabetical letters and spaces: yes

编辑2:根据您的新评论判断,您需要以下内容:def hasSpaceAndAlpha(string):

return any(char.isalpha() for char in string) and any(char.isspace() for char in string) and all(char.isalpha() or char.isspace() for char in string)

>>> hasSpaceAndAlpha("text# ")

False

>>> hasSpaceAndAlpha("text")

False

>>> hasSpaceAndAlpha("text ")

True

或者def hasSpaceAndAlpha(string):

if any(char.isalpha() for char in string) and any(char.isspace() for char in string) and all(char.isalpha() or char.isspace() for char in string):

print("Only alphabetical letters and spaces: yes")

else:

print("Only alphabetical letters and spaces: no")

>>> hasSpaceAndAlpha("text# ")

Only alphabetical letters and spaces: no

>>> hasSpaceAndAlpha("text")

Only alphabetical letters and spaces: no

>>> hasSpaceAndAlpha("text ")

Only alphabetical letters and spaces: yes

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值