Python program for handling empty strings
3. Iterate and Print Strings
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:

For more Practice: Solve these Related Problems:
- Write a Python program to iterate over a list of strings and print each string; if a string is empty, print "Empty string" instead.
- Write a Python script that processes a list of strings and uses a conditional expression to print "Empty string" for any element that is empty.
- Write a Python program that loops through a list of strings, checking for emptiness, and collects non-empty strings into a new list while marking empties.
- Write a Python function to iterate through a list of strings, printing each string normally or "Empty string" if the string length is zero, then return the count of empty strings.
Python Code Editor :
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.