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

后端 未结 11 2291
北恋
北恋 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:18

    if the variable contains text then:

    len(variable) != 0

    of it does not

    len(variable) == 0

    0 讨论(0)
  • 2020-12-23 19:20
    string = "TEST"
    try:
      if str(string):
         print "good string"
    except NameError:
         print "bad string"
    
    0 讨论(0)
  • 2020-12-23 19:21

    The "Pythonic" way to check if a string is empty is:

    import random
    variable = random.choice(l)
    if variable:
        # got a non-empty string
    else:
        # got an empty string
    
    0 讨论(0)
  • 2020-12-23 19:24
    element = random.choice(myList)
    if element:
        # element contains text
    else:
        # element is empty ''
    
    0 讨论(0)
  • 2020-12-23 19:30

    You could just compare your string to the empty string:

    if variable != "":
        etc.
    

    But you can abbreviate that as follows:

    if variable:
        etc.
    

    Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.

    0 讨论(0)
提交回复
热议问题