How to check whether a str(variable) is empty or not?

后端 未结 11 2320
北恋
北恋 2020-12-23 18:27

How do I make a:

if str(variable) == [contains text]:

condition?

(or something, because I am pretty sure that what I just wrote is

相关标签:
11条回答
  • 2020-12-23 19:05

    For python 3, you can use bool()

    >>> bool(None)
    False
    >>> bool("")
    False
    >>> bool("a")
    True
    >>> bool("ab")
    True
    >>> bool("9")
    True
    
    0 讨论(0)
  • 2020-12-23 19:06

    Some time we have more spaces in between quotes, then use this approach

    a = "   "
    >>> bool(a)
    True
    >>> bool(a.strip())
    False
    
    if not a.strip():
        print("String is empty")
    else:
        print("String is not empty")
    
    0 讨论(0)
  • 2020-12-23 19:11

    use "not" in if-else

    x = input()
    
    if not x:
       print("Value is not entered")
    else:
       print("Value is entered")
    
    0 讨论(0)
  • 2020-12-23 19:12

    How do i make an: if str(variable) == [contains text]: condition?

    Perhaps the most direct way is:

    if str(variable) != '':
      # ...
    

    Note that the if not ... solutions test the opposite condition.

    0 讨论(0)
  • 2020-12-23 19:15

    Just say if s or if not s. As in

    s = ''
    if not s:
        print 'not', s
    

    So in your specific example, if I understand it correctly...

    >>> import random
    >>> l = ['', 'foo', '', 'bar']
    >>> def default_str(l):
    ...     s = random.choice(l)
    ...     if not s:
    ...         print 'default'
    ...     else:
    ...         print s
    ... 
    >>> default_str(l)
    default
    >>> default_str(l)
    default
    >>> default_str(l)
    bar
    >>> default_str(l)
    default
    
    0 讨论(0)
  • 2020-12-23 19:17

    Empty strings are False by default:

    >>> if not "":
    ...     print("empty")
    ...
    empty
    
    0 讨论(0)
提交回复
热议问题