检查字符串是否只是字母和空格 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29460405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:35:38  来源:igfitidea点击:

Checking if string is only letters and spaces - Python

pythoncontain

提问by sithlorddahlia

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

试图让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")

I've been trying pleaseand it comes up as Only alphabetical letters and spaces: noI've used orinstead of and, but that only satisfies one condition. I need both conditions satisfied. That is the sentence must contain only lettersand only spacesbut must have at least one of each kind. It must notcontain any numerals.

我一直在尝试please,它出现了,因为Only alphabetical letters and spaces: no我使用了or而不是and,但这仅满足一个条件。我需要满足这两个条件。那就是句子必须包含字母空格,但必须至少有一个。它不得包含任何数字。

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

我在这里缺少什么让python返回字母和空格只包含在字符串中?

采纳答案by rob mayoff

A character cannot be both an alpha anda space. It can be an alpha ora space.

一个字符不能既是字母是空格。它可以是 alpha空格。

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

Test:

测试:

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

回答by codingEnthusiast

The correct solution would use an or.

正确的解决方案是使用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")

Although you have a string, you are iterating over the letters of that string, so you have one letter at a time. So, a char alone cannot be an alphabetical character AND a space at the time, but it will just need to be one of the two to satisfy your constraint.

尽管您有一个字符串,但您正在迭代该字符串的字母,因此一次只有一个字母。所以,一个字符在当时不能是一个字母字符和一个空格,但它只需要成为两者之一来满足你的约束。

EDIT:I saw your comment in the other answer. alphabet = string.isalpha()return True, if and only if allcharacters in a string are alphabetical letters. This is not what you want, because you stated that you want your code to print yeswhen execute with the string please, which has a space. You need to check each letter on its own, not the whole string.

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

Just to convince you that the code is indeed correct (well, ok, you need to execute it yourself to be convinced, but anyway):

只是为了让你相信代码确实是正确的(好吧,好吧,你需要自己执行才能被说服,但无论如何):

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

EDIT 2:Judging from your new comments, you need something like this:

编辑 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

or

或者

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

回答by Padraic Cunningham

You need anyif you want at least one of each in the string:

如果您想要字符串中的至少一个,则需要任何一个:

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

If you want at least one of each but no other characters you can combine all,anyand str.translate, the following will only return Trueif we have at least one space, one alpha and contain only those characters.

如果你希望每个的至少一个,但你可以将任何其它字符allany并且str.translate,下面就只返回True,如果我们至少有一个空间,一个字母,并且只包含这些字符。

 from string import ascii_letters

 s = input("Enter a string: ")

 tbl = {ord(x):"" for x in ascii_letters + " "}

if all((any(x.isalpha() for x in s),
   any(x.isspace() for x in s),
   not s.translate(tbl))):
    print("all good")

Check if there is at least one of each with anythen translate the string, if the string is empty there are only alpha characters and spaces. This will work for upper and lowercase.

检查每个是否至少有一个,any然后翻译字符串,如果字符串为空,则只有字母字符和空格。这适用于大写和小写。

You can condense the code to a single if/and:

您可以将代码压缩为一个if/and

from string import ascii_letters

s = input("Enter a string: ")
s_t = s.translate({ord(x):"" for x in ascii_letters})

if len(s_t) < len(s) and s_t.isspace():
    print("all good")

If the length of the translated string is < original and all that is left are spaces we have met the requirement.

如果翻译后的字符串长度< original 并且剩下的都是空格,我们就满足了要求。

Or reverse the logic and translate the spaces and check if we have only alpha left:

或者颠倒逻辑并转换空格并检查我们是否只剩下alpha:

s_t = s.translate({ord(" "):"" })
if len(s_t) < len(s) and s_t.isalpha():
    print("all good")

Presuming the string will always have more alphas than spaces, the last solution should be by far the most efficient.

假设字符串总是比空格有更多的字母,最后一个解决方案应该是迄今为止最有效的。

回答by flaschbier

Actually, it is an pattern matching exercise, so why not use pattern matching?

其实就是模式匹配练习,为什么不使用模式匹配呢?

import re
r = re.compile("^[a-zA-Z ]*$")
def test(s):
    return not r.match(s) is None  

Or is there any requirement to use any()in the solution?

或者any()在解决方案中使用有什么要求吗?

回答by vikash chand singh

    string = input("Enter a string: ")
    st1=string.replace(" ","").isalpha()
    if (st1):
        print("Only alphabetical letters and spaces: yes")
    else:
        print("Only alphabetical letters and spaces: no")