2024-05-23 15:30:28 发布
网友
我想测试一个句子是否包含除空格字符以外的任何内容。这是我目前使用的:
if len(teststring.split()) > 0: # contains something else than white space else: # only white space
这够好吗?有更好的方法吗?
字符串有一个名为^{}的方法,根据文档:
Return[s] true if there are only whitespace characters in the string and there is at least one character, false otherwise.
所以,这意味着:
if teststring.isspace(): # contains only whitespace
会做你想做的。
为此,我将使用strip()函数。
if teststring.strip(): # non blank line else: # blank line
你可以使用.strip()。
如果结果字符串仅为空白,则该字符串将为空。
if teststring.strip(): # has something other than whitespace. else: # only whitespace
或者更明确地说,正如JBernardo所指出的:
if not teststring.isspace(): # has something other than whitespace else: # only whitespace.
字符串有一个名为^{} 的方法,根据文档:
所以,这意味着:
会做你想做的。
为此,我将使用strip()函数。
你可以使用.strip()。
如果结果字符串仅为空白,则该字符串将为空。
或者更明确地说,正如JBernardo所指出的:
相关问题 更多 >
编程相关推荐