拒绝只包含空格的字符串



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

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

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

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

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

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

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

要避免整个字符串类仅由空白组成,您可以使用str.strip:

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

This?

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

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

最新更新