检查字符串是否仅是字母和空格-Python [英] Checking if string is only letters and spaces - Python

查看:410
本文介绍了检查字符串是否仅是字母和空格-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让python返回一个仅包含字母和空格的字符串

Trying to get python to return that a string contains ONLY alphabetic letters AND spaces

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")

I'一直尝试,它显示为仅字母和空格:否我用过而不是,但这仅满足一个条件。我需要两个条件都满足。也就是说,该句子必须包含仅字母仅空格,但每种类型必须至少包含一个。它必须包含任何数字。

I've been trying please and it comes up as Only alphabetical letters and spaces: no I've used or instead of and, but that only satisfies one condition. I need both conditions satisfied. That is the sentence must contain only letters and only spaces but must have at least one of each kind. It must not contain any numerals.

我在这里缺少什么让python返回仅包含在字符串中的字母和空格吗? / p>

What am I missing here for python to return both letters and spaces are only contained in the string?

推荐答案

字符不能同时是字母。可以是字母空格。

A character cannot be both an alpha and a space. It can be an alpha or a space.

要求字符串仅包含字母和空格:

To require that the string contains only alphas and spaces:

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")

要求字符串包含至少一个字母和至少一个空格:

To require that the string contains at least one alpha and at least one space:

if any(x.isalpha() for x in string) and any(x.isspace() for x in string):

要求字符串包含至少一个字母,至少一个空格以及仅字母和空格:

To require that the string contains at least one alpha, at least one space, and only alphas and spaces:

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

测试:

>>> string = "PLEASE"
>>> if (any(x.isalpha() for x in string)
...     and any(x.isspace() for x in string)
...     and all(x.isalpha() or x.isspace() for x in string)):
...     print "match"
... else:
...     print "no match"
... 
no match
>>> string = "PLEASE "
>>> if (any(x.isalpha() for x in string)
...     and any(x.isspace() for x in string)
...     and all(x.isalpha() or x.isspace() for x in string)):
...     print "match"
... else:
...     print "no match"
... 
match

这篇关于检查字符串是否仅是字母和空格-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆