Inline if

Yesterday I had to concatenate a string to another string in Python, but only if the latter is not None.
None cannot be concatenated:

x = None
res = "I like " + x + " summer."

gives

TypeError: cannot concatenate 'str' and 'NoneType' objects

After some research I tried the following:

x = None
res = "I like " + x if x + " summer."

gives

SyntaxError: invalid syntax

So I tried the following:

x = None
res = "I like " + x if x else "" + " summer."

But the result was

print(res)
' summer.'

Oups! what I wrote meant

res = ("I like " + x) if x else "" + " summer."

So the final fix for the problem was:

x = None
res = "I like " + (x if x else "") + " summer."
print(res)
x = "the"
res = "I like " + (x if x else "") + " summer."
print(res)

which gives:

"I like summer."
"I like the summer."
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s