hel*_*ase 4 python string for-loop python-3.x
我无法弄清楚上面的问题并且有一个感觉我应该用"为字符串中的字符"测试每个字符但是我无法弄清楚它是如何工作的
这就是我现在所拥有但我知道它不能按预期工作,因为它只允许我测试字母,但我也需要知道空格,例如"我亲爱的阿姨莎莉"应该说是只包含字母和空格
#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")
Run Code Online (Sandbox Code Playgroud)
您可以在内置函数中使用生成器表达式all:
if all(i.isalpha() or i.isspace() for i in my_string)
Run Code Online (Sandbox Code Playgroud)
但请注意,i.isspace()如果您只是想要space直接与空间进行比较,将检查字符是否为空格:
if all(i.isalpha() or i==' ' for i in my_string)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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
Run Code Online (Sandbox Code Playgroud)