问题
How can I test if the string is empty in Python?
For example,
"<space><space><space>"
is empty, so is
"<space><tab><space><newline><space>"
, so is
"<newline><newline><newline><tab><newline>"
, etc.
回答1:
yourString.isspace()
"Return true if there are only whitespace characters in the string and there is at least one character, false otherwise."
Combine that with a special case for handling the empty string.
Alternatively, you could use
strippedString = yourString.strip()
And then check if strippedString is empty.
回答2:
>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [bool(not s or s.isspace()) for s in tests]
[False, True, True, True, True]
>>>
回答3:
You want to use the isspace() method
str.isspace()
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
That's defined on every string object. Here it is an usage example for your specific use case:
if aStr and (not aStr.isspace()):
print aStr
回答4:
isspace
回答5:
for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
回答6:
Check the length of the list given by of split() method.
if len(your_string.split()==0:
print("yes")
Or Compare output of strip() method with null.
if your_string.strip() == '':
print("yes")
回答7:
Here is an answer that should work in all cases:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
If the variable is None, it will stop at not s
and not evaluate further (since not None == True
). Apparently, the strip()
method takes care of the usual cases of tab, newline, etc.
回答8:
I'm assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.
if(str.strip()):
print("string is not empty")
else:
print("string is empty")
Note this does not check for None
回答9:
I used following:
if str and not str.isspace():
print('not null and not empty nor whitespace')
else:
print('null or empty or whitespace')
回答10:
To check if a string is just a spaces or newline
Use this simple code
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)
回答11:
Resemblence with c# string static method 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
来源:https://stackoverflow.com/questions/2405292/how-to-check-if-text-is-empty-spaces-tabs-newlines-in-python