Explore Non-Empty Strings
In this step, we will explore how to determine if a string is non-empty in Python. A non-empty string is simply a string that contains at least one character. There are several ways to check for this condition, and we'll cover the most common and efficient methods.
First, let's create a Python file named string_check.py
in your ~/project
directory using the VS Code editor.
## ~/project/string_check.py
string1 = "Hello"
string2 = ""
if string1:
print("string1 is non-empty")
else:
print("string1 is empty")
if string2:
print("string2 is non-empty")
else:
print("string2 is empty")
In this code:
- We define two strings:
string1
which contains "Hello", and string2
which is an empty string.
- We use the
if string1:
and if string2:
statements to check if the strings are non-empty. In Python, an empty string evaluates to False
in a boolean context, while a non-empty string evaluates to True
.
Now, let's run the script using the python
command:
python ~/project/string_check.py
You should see the following output:
string1 is non-empty
string2 is empty
This demonstrates that Python correctly identifies string1
as non-empty and string2
as empty.
Another way to check if a string is non-empty is to use the len()
function. The len()
function returns the number of characters in a string. If the length is greater than 0, the string is non-empty.
Let's modify the string_check.py
file to use the len()
function:
## ~/project/string_check.py
string1 = "Hello"
string2 = ""
if len(string1) > 0:
print("string1 is non-empty")
else:
print("string1 is empty")
if len(string2) > 0:
print("string2 is non-empty")
else:
print("string2 is empty")
Run the script again:
python ~/project/string_check.py
The output will be the same as before:
string1 is non-empty
string2 is empty
Both methods are valid for checking if a string is non-empty. The first method (using the string directly in a boolean context) is generally considered more Pythonic and readable.