如何判断一个字符串是否只包含空格?
示例字符串:
" "
(空格,空格,空格)" \t \n "
(空格,制表符,换行符,空格)"\n\n\n\t\n"
(换行符,换行符,换行符,制表符,换行符)
如何判断一个字符串是否只包含空格?
示例字符串:
" "
(空格,空格,空格)
" \t \n "
(空格,制表符,换行符,空格)
"\n\n\n\t\n"
(换行符,换行符,换行符,制表符,换行符)
使用str.isspace()
方法:
如果字符串中只有空格字符且至少有一个字符,则返回
True
,否则返回False
。如果字符在Unicode字符数据库(见unicodedata)中的一般类别为Zs(“分隔符,空格”),或其双向类别为WS、B或S之一,则该字符为空格。
将其与处理空字符串的特殊情况相结合。
或者,您可以使用str.strip()
并检查结果是否为空。
U+00A0
或者ALT+160
,这段代码在Python 2.4上会失败。但是在Python 2.7中已经修复了这个问题。 - KumbaNone
或''
。 - Parth Mehrotraif len(str) == 0 or str.isspace():
- Joe"".isspace()
返回 False
真的是一个非常大的 WTF。 - Timmmmstr.isspace() 对于一个有效且为空的字符串返回 False
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
not
进行检查也将评估None
类型和''
或""
(空字符串)。>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
None
时返回True
? - AMC对于那些期望像Apache StringUtils.isBlank或Guava Strings.isNullOrEmpty一样的行为的人:
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
if len(your_string.split()==0:
print("yes")
或者将strip()方法的输出与null进行比较。
if your_string.strip() == '':
print("yes")
len()
适用于字符串。此外,OP 并不是在询问如何测试空字符串,而是要测试一个全为空格的字符串。你的第二种方法也不错。此外,在 Python 中,条件语句周围的括号是不必要的。 - NeilK==0
替换为==1
。 - Mad Physicistif len(your_string.split())==0:
--> if not your_string.split():
, if your_string.strip() == '':
--> if not your_string.strip():
。无论哪种情况,第一种方法都不如现有的解决方案好,而第二种方法已经在其他答案中提到过了。 - AMC类似于C#字符串静态方法isNullOrWhiteSpace。
def isNullOrWhiteSpace(str):
"""Indicates whether the specified string is null or empty string.
Returns: True if the str parameter is null, an empty string ("") or contains
whitespace. Returns false otherwise."""
if (str is None) or (str == "") or (str.isspace()):
return True
return False
isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("") -> True
isNullOrWhiteSpace(" ") -> True
return (str is None) or (str == "") or (str.isspace())
。 - AlexanderNone
和""
都是假的,所以你可以这样写:return not str or str.isspace()
。 - Alexander这里是一个适用于所有情况的解决方案:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
not s
处停止并且不再进一步进行评估(因为not None == True
)。显然,strip()
方法处理了制表符、换行符等常见情况。not None == True
会产生歧义,最好直接说 None is False
。此外,这种比较不应使用 ==
。 - AMC我使用了以下内容:
if str and not str.isspace():
print('not null and not empty nor whitespace')
else:
print('null or empty or whitespace')
None
吗? - AMC我假设在您的情况下,空字符串是一个真正为空或只包含所有空格的字符串。
if(str.strip()):
print("string is not empty")
else:
print("string is empty")
None
。