【发布时间】:2011-01-25 04:56:37
【问题描述】:
如何测试字符串是否只包含空格?
示例字符串:
-
" "(空格、空格、空格) -
" \t \n "(空格、制表符、空格、换行符、空格) -
"\n\n\n\t\n"(换行符、换行符、换行符、制表符、换行符)
【问题讨论】:
-
换行符是空格吗? Tab 应该是一对多的空格。
标签: python text whitespace
如何测试字符串是否只包含空格?
示例字符串:
" "(空格、空格、空格)
" \t \n "(空格、制表符、空格、换行符、空格)
"\n\n\n\t\n"(换行符、换行符、换行符、制表符、换行符)
【问题讨论】:
标签: python text whitespace
使用str.isspace() 方法:
如果字符串中只有空白字符且至少有一个字符,则返回
True,否则返回False。如果在 Unicode 字符数据库(参见 unicodedata)中,一个字符是空白字符,或者它的一般类别是 Zs(“分隔符,空格”),或者它的双向类是 WS、B 或 S 之一。
将其与处理空字符串的特殊情况结合起来。
或者,您可以使用str.strip() 并检查结果是否为空。
【讨论】:
U+00A0 或 ALT+160,则在 Python 2.4 中将失败。但是,在 Python 2.7 中看起来已修复。
None 或 ''
if len(str) == 0 or str.isspace():
len(my_str) == 0 也可以写成not my_str。
您可以使用str.isspace() 方法。
【讨论】:
str.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]
【讨论】:
True for None?
你想使用isspace()方法
str.isspace()
如果字符串中只有空白字符,则返回 true 并且 至少有一个字符,否则为假。
这是在每个字符串对象上定义的。这是您特定用例的使用示例:
if aStr and (not aStr.isspace()):
print aStr
【讨论】:
检查 split() 方法给出的列表的长度。
if len(your_string.split()==0:
print("yes")
或者 将 strip() 方法的输出与 null 进行比较。
if your_string.strip() == '':
print("yes")
【讨论】:
len() 适用于字符串。此外,OP 并没有要求测试空字符串,而是要求测试一个全是空格的字符串。你的第二种方法虽然不错。此外,python 中不需要围绕条件的括号。
==0替换为==1
if len(your_string.split())==0: --> if not your_string.split():, if your_string.strip() == '': --> if not your_string.strip():.无论如何,第一个不如现有的解决方案,第二个已经在其他答案中提到过。
对于那些期望像 apache StringUtils.isBlank 或 Guava Strings.isNullOrEmpty 这样的行为的人:
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
【讨论】:
我假设在您的场景中,空字符串是真正为空的字符串或包含所有空格的字符串。
if(str.strip()):
print("string is not empty")
else:
print("string is empty")
请注意,这不会检查 None
【讨论】:
这是一个适用于所有情况的答案:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
如果变量为 None,它将在 not s 处停止并且不会进一步评估(因为 not None == True)。显然,strip() 方法处理了制表符、换行符等常见情况。
【讨论】:
not None == True 直接说None is False 可能更清楚。此外,== 不应用于这些比较。
我用了以下:
if str and not str.isspace():
print('not null and not empty nor whitespace')
else:
print('null or empty or whitespace')
【讨论】:
None 吗?
检查字符串是否只是空格或换行符
使用这个简单的代码
mystr = " \n \r \t "
if not mystr.strip(): # The String Is Only Spaces!
print("\n[!] Invalid String !!!")
exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)
【讨论】:
类似于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())
None 和 "" 都是假的,所以你可以:return not str or str.isspace()