如何检查字符串是否仅包含 Python 中的字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18667410/
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 11:23:02  来源:igfitidea点击:

How can I check if a string only contains letters in Python?

pythonstringconditional-statements

提问by user2745401

I'm trying to check if a string only contains letters, not digits or symbols.

我试图检查一个字符串是否只包含字母,而不是数字或符号。

For example:

例如:

>>> only_letters("hello")
True
>>> only_letters("he7lo")
False

回答by cmd

The str.isalpha()function works. ie.

str.isalpha()功能有效。IE。

if my_string.isalpha():
    print('it is letters')

回答by Martijn Pieters

Simple:

简单的:

if string.isalpha():
    print("It's all letters")

str.isalpha()is only true if allcharacters in the string are letters:

str.isalpha()仅当字符串中的所有字符都是字母时才为真:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

如果字符串中的所有字符都是字母并且至少有一个字符,则返回 true,否则返回 false。

Demo:

演示:

>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False

回答by Amilcar Andrade

The string.isalpha()function will work for you.

string.isalpha()功能将为您工作。

See http://www.tutorialspoint.com/python/string_isalpha.htm

http://www.tutorialspoint.com/python/string_isalpha.htm

回答by Martin Thoma

For people finding this question via Google who might want to know if a string contains only a subset of all letters, I recommend using regexes:

对于通过谷歌发现这个问题的人,他们可能想知道一个字符串是否只包含所有字母的一个子集,我建议使用正则表达式:

import re

def only_letters(tested_string):
    match = re.match("^[ABCDEFGHJKLM]*$", tested_string)
    return match is not None

回答by The SuperCuber

A pretty simple solution I came up with: (Python 3)

我想出了一个非常简单的解决方案:(Python 3)

def only_letters(tested_string):
    for letter in tested_string:
        if letter not in "abcdefghijklmnopqrstuvwxyz":
            return False
    return True

You can add a space in the string you are checking against if you want spaces to be allowed.

如果您希望允许使用空格,您可以在要检查的字符串中添加一个空格。

回答by hlin117

Looks like people are saying to use str.isalpha.

看起来人们说要使用str.isalpha.

This is the one line function to check if all characters are letters.

这是检查所有字符是否都是字母的单行函数。

def only_letters(string):
    return all(letter.isalpha() for letter in string)

allaccepts an iterable of booleans, and returns Trueiff all of the booleans are True.

all接受一个可迭代的布尔值,True如果所有的布尔值都是True.

More generally, allreturns Trueif the objects in your iterable would be considered True. These would be considered False

更一般地,如果您的可迭代对象中的对象被考虑,则all返回。这些会被考虑TrueTrueFalse

  • 0
  • None
  • Empty data structures (ie: len(list) == 0)
  • False. (duh)
  • 0
  • None
  • 空数据结构(即:len(list) == 0
  • False. (废话)

回答by kravietz

Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedatalibrary which among other things allows categorization of Unicode characters:

实际上,我们现在处于 21 世纪的全球化世界,人们不再仅使用 ASCII 进行通信,因此在回答有关“是否仅使用字母”的问题时,您还需要考虑非 ASCII 字母表中的字母。Python 有一个非常酷的unicodedata库,它允许对 Unicode 字符进行分类:

unicodedata.category('陳')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviationsare defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

类别和它们的缩写在Unicode标准定义。从这里你可以很容易地想出这样的函数:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

进而:

only_letters('Bzdr??y?o')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this articlefor a more detailed discussion.

如您所见,列入白名单的类别可以很容易地由函数内的元组控制。有关更详细的讨论,请参阅本文

回答by Hemin Patel

(1) Use str.isalpha()when you print the string.

(1)打印字符串时使用str.isalpha()

(2) Please check below program for your reference:-

(2) 请检查以下程序以供您参考:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:-I checked above example in Ubuntu.

注意:-我在 Ubuntu 中检查了上面的例子。

回答by Shail

You can leverage regular expressions.

您可以利用正则表达式。

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

The match()method will return a Matchobject if a match is found. Otherwise it will return None.

如果找到匹配项,该match()方法将返回一个Match对象。否则它会返回None



An easier approach is to use the .isalpha()method

更简单的方法是使用.isalpha()方法

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha()returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.

isalpha()如果字符串中至少有 1 个字符并且字符串中的所有字符都是字母,则返回 true。