w3resource

Python program for handling empty strings

Python None Data Type: Exercise-3 with Solution

Write a Python program that iterates through a list of strings and prints each string. If a string is empty, print "Empty string" instead.

Sample Solution:

Code:

def empty_string_handling(string_list):
    for s in string_list:
        if s:
            print(s)
        else:
            print(None)

def main():
    try:
        text_list = ["Python", "", "Java", "C++", "", "C#"]
        empty_string_handling(text_list)
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Python
None
Java
C++
None
C#

In the exercise above, the "empty_string_handling()" function uses the boolean value of each string to decide whether to print the string itself or 'None'. If the string is not empty, it evaluates to 'True' and is printed. Otherwise, it evaluates to 'False' and 'None' is printed.

Flowchart:

Flowchart: Python program for handling empty strings.

Previous: Python function to retrieve middle character.
Next: Check descending sort & empty list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-none-exercise-3.php