拒绝只包含空格的字符串

Reject strings that only contain spaces

我有以下代码来输入一个字符串,并在某些情况下拒绝它:

x = input() 
while x.count('')>=1:  
    print('type non empty text only')
    x = input()

但是,我想拒绝仅包含 space 的字符串,并接受包含至少一个非 space 字符的所有字符串。上面的代码错误地拒绝了许多应该接受的字符串。

应接受或拒绝的字符串示例:

'   '   ->  reject
''      ->  reject
'   a ' ->  accept

这个?

x = input() 
while len(x)==0 or set(x) == {' '}:
    print('type non empty text only')
    x = input() 

while all(c==' ' for c in x):

为了避免整个 class 字符串只由白色 space 组成,您可以使用 str.strip:

while not (x := input()).strip():  
    print('type non empty text only')

IIUC,您可以使用 str.strip() 并使用 '' 检查,如下所示:

x = input() 
while x.strip() == '':
    print('type non empty text only')
    x = input()