How to Concatenate Strings in Python When Not Empty and Append When Empty?

Estimated read time 2 min read

To concatenate strings in Python when one of them is empty, you can use a conditional statement to check if the string is empty or not. Here’s an example:

str1 = "Hello"
str2 = ""

if str2:
    concatenated_string = str1 + str2
    concatenated_string = str1


In this example, we have two strings, str1 and str2. We use an if statement to check if str2 is not empty (evaluates to True). If str2 is not empty, we concatenate it with str1 using the + operator. Otherwise, we assign str1 to the concatenated_string variable.

The condition if str2 checks if str2 has any non-empty content. If it is an empty string or evaluates to False, the condition will be False, and the else block will be executed.

Alternatively, you can use a conditional expression (ternary operator) to achieve the same result in a more concise way:

str1 = "Hello"
str2 = ""

concatenated_string = str1 + str2 if str2 else str1


In this case, the conditional expression conditionally concatenates str1 and str2 only if str2 is not empty. If str2 is empty, it assigns str1 to concatenated_string.

By checking if the string is empty or not, you can concatenate the strings accordingly, either by appending the non-empty string or just using the non-empty string itself.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply