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