How to Concatenate Strings in Python When One is Null?

Estimated read time 2 min read

When concatenating strings in Python, if one of the strings is None or null, you need to handle it appropriately to avoid any errors. Here’s an example of how you can concatenate strings when one of them is None:

str1 = "Hello"
str2 = None

if str2 is not None:
    concatenated_string = str1 + str2
else:
    concatenated_string = str1

print(concatenated_string)

In this example, we have two strings, str1 and str2. If str2 is not None, we can safely concatenate it with str1. However, if str2 is None, we simply assign str1 to the concatenated_string variable.

By using the if statement to check if the string is None, we can handle the case where one of the strings is None and avoid any potential errors when concatenating.

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

str1 = "Hello"
str2 = None

concatenated_string = str1 + str2 if str2 is not None else str1

print(concatenated_string)

This conditional expression conditionally concatenates str1 and str2 only if str2 is not None. Otherwise, it assigns str1 to concatenated_string.

By handling the case where one of the strings is None, you can safely concatenate the strings without causing any errors.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply