[英]Testing string content on non-whitespace
我想测试一个句子是否包含除空白字符以外的任何内容。 这是我目前使用的:
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
这够好吗? 有没有更好的方法呢?
字符串有一个名为str.isspace
的方法,根据文档:
如果字符串中只有空格字符并且至少有一个字符,则返回[s] true,否则返回false。
所以,这意味着:
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.
if teststring.split():
print "not only whitespace!"
else:
print ":("
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.