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

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

我无法弄清楚上述问题,我觉得我应该用“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")

最佳答案

您可以在 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

关于python - 如何判断一个字符串是否只包含字母和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29454773/

相关文章:

python - Microsoft Python 语言服务器无法识别 `for` 循环 `zip()`

python - 如何在 Telegram Bot 中获取用户名?

python - 是否有可插拔的在线 python 控制台?

python - 如何在 mac os x 上安装 leveldb

python - torchvision.io 在 __init.py__ 中找不到引用 read_image()

Python tkinter 如何使用网格粘性

c - 字符串未正确转换为小写

linux - 检查 Zabbix 触发器中两个字符串类型项的值是否相等

java - 从文件读取时的 String.contains()

python - 如何打印队列前面的元素python 3?