【问题标题】:How can I tell if a string only contains letter AND spaces如何判断字符串是否仅包含字母和空格
【发布时间】:2015-06-09 21:02:30
【问题描述】:

我无法弄清楚上述问题并且有一种感觉,我应该用“for character in string”测试每个字符,但是我真的不知道它是如何工作的

这是我现在拥有的,但我知道它不能按预期工作,因为它只允许我测试字母但我还需要知道空格,例如“MY Dear aunt sally”应该说是只包含字母和空格

    #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吗?

标签: python string python-3.x for-loop


【解决方案1】:

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

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

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

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,我认为 op 想要返回 false。
  • @AvinashRaj mmm,我不这么认为,因为我看不到有问题的东西,无论如何我都需要等待 OP 的回复!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    replaceisalpha 级联:

    'a b'.replace(' ', '').isalpha() # True
    

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

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

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

    【讨论】:

      【解决方案4】:

      只有当输入包含字母或空格时,下面的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')
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2020-08-26
        • 1970-01-01
        • 2011-02-24
        • 1970-01-01
        • 2011-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多