Most elegant way to check if the string is empty i

2019-01-01 04:38发布

Does Python have something like an empty string variable where you can do?:

if myString == string.empty:

Regardless what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.

22条回答
冷夜・残月
2楼-- · 2019-01-01 04:49

Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

However if you must treat None and (spaces) as "blank" strings, here is a better way:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

Examples:

>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
... 
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.

查看更多
美炸的是我
3楼-- · 2019-01-01 04:53

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"
查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 04:56

If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip.

查看更多
刘海飞了
5楼-- · 2019-01-01 04:58
if my_string is '':

I haven't noticed THAT particular combination in any of the answers. I searched for

is ''

in the answers prior to posting.

 if my_string is '': print ('My string is EMPTY') # **footnote

I think this is what the original poster was trying to get to... something that reads as close to English as possible and follows solid programming practices.

if my_string is '':
    print('My string is EMPTY')
else:
    print(f'My string is {my_string}')

Character for character I think this solution is a good one.

I noted None has entered into the discussion, so adding that and compacting further we get:

if my_string is '': print('My string is Empty')
elif my_string is None : print('My string.... isn\'t')
else: print(f'My string is {my_string}')
查看更多
情到深处是孤独
6楼-- · 2019-01-01 04:59

Test empty or blank string (shorter way):

if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")
查看更多
呛了眼睛熬了心
7楼-- · 2019-01-01 04:59

if stringname: gives a false when the string is empty. I guess it can't be simpler than this.

查看更多
登录 后发表回答