如何判断字符串是否只包含字母和空格

4

我有困难理解上述问题,感觉应该使用“for character in string”测试每个字符,但我无法弄清楚它是如何工作的。

这是我现在拥有的,但我知道它不能正常工作,因为它只允许我测试字母,但我还需要知道空格,例如“我的亲爱的姑妈莎莉”应该说是只包含字母和空格。

    #Find if string only contains letters and spaces
    if string.isalpha():
      print("Only alphabetic letters and spaces: yes")
    else:
      print("Only alphabetic letters and spaces: no")

你希望这个函数对于 foo 返回 true 吗? - Avinash Raj
4个回答

5

您可以在内置函数all中使用生成器表达式

if all(i.isalpha() or i.isspace() for i in my_string)

请注意,i.isspace()将检查字符是否为空格,如果您只想要空格,则可以直接与空格进行比较:

if all(i.isalpha() or i==' ' for i in my_string)

演示:

>>> all(i.isalpha() or i==' ' for i in 'test string')
True
>>> all(i.isalpha() or i==' ' for i in 'test    string') #delimiter is tab
False
>>> all(i.isalpha() or i==' ' for i in 'test#string')
False
>>> all(i.isalpha() or i.isspace() for i in 'test string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test       string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test@string')
False

但它对于“teststring”返回true,我认为操作者想要返回false。 - Avinash Raj
@AvinashRaj 嗯,我不这么认为,因为我在问题中看不到这样的东西,无论如何,我需要等待OP的回复! - Mazdak

1

只是另一种有趣的方式,我知道它不是很好:

>>> a
'hello baby'
>>> b
'hello1 baby'
>>> re.findall("[a-zA-Z ]",a)==list(a)  # return True if string is only alpha and space
True
>>> re.findall("[a-zA-Z ]",b)==list(b) # returns False
False

0
将程序中的“replace”替换为“isalpha”:
'a b'.replace(' ', '').isalpha() # True

replace 返回一个除空格以外的原始字符串副本。然后,您可以对该返回值(因为返回值本身是一个字符串)使用 isalpha 来测试它是否只包含字母字符。

要匹配所有空白字符,您可能需要使用 Kasra 的答案,但为了完整起见,我将演示如何使用带有空格字符类的 re.sub

import re
re.sub(r'\s', '', 'a b').isalpha()

0
以下的re.match函数只会在输入包含字母或空格时返回匹配对象。
>>> re.match(r'[A-Za-z ]+$', 'test string')
<_sre.SRE_Match object; span=(0, 11), match='test string'>
>>> re.match(r'(?=.*? )[A-Za-z ]+$', 'test@bar')
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接