Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I make a:

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

condition?

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

I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].

like image 374
user1275670 Avatar asked Mar 29 '12 13:03

user1275670


People also ask

How check string is empty variable?

If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty. Copied! If you consider an empty string one that contains only spaces, use the trim() method to remove any leading or trailing whitespace before checking if it's empty.

How do you know if a variable is empty?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How do I check if a string is empty in Python?

To check an empty string in Python, use the len() function; if it returns 0, that means the string is empty; otherwise, it is not. So, if the string has something, it will count as a non-empty string; otherwise, it is an empty string.

How check if string is empty C#?

C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


1 Answers

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.

like image 188
alexis Avatar answered Oct 24 '22 07:10

alexis