Reputation: 27
This:
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
and this:
w = "This is the left side of..." e = "a string with a right side."
print w + e
Seem to be doing the same thing. Why can't I change the code to read:
print joke_evaluation + hilarious
Why doesn't this work?
Upvotes: 1
Views: 194
Reputation: 1
This was quite confusing to me as well, but it seems that due to it being a Boolean value you cannot use +.
If you do you get an error like this:
TypeError: cannot concatenate 'str' and 'bool' objects
Upvotes: 0
Reputation: 27
This is what was confusing me:
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
I would prefer it to look like this:
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r" % hilarious
print joke_evaluation
I guess it just looked funky to my eyes.
Upvotes: 0
Reputation: 8925
%r
calls repr()
, which represents False
(bool) as "False"
(string).
+
can only be used to concatenate a string with other strings (Otherwise you get a TypeError: cannot concatenate 'str' and 'bool' objects
)
You can convert False
to a string before you concatenate it:
>>> print "Isn't that joke so funny?!" + str(False)
You could also try new string formatting:
>>> print "Isn't that joke so funny?! {!r}".format(False)
Isn't that joke so funny?! False
Upvotes: 6
Reputation: 276
This is a type conversion issue. When you are trying to concatenate to a string in Python, you may only concatenate other strings. You are attempting to concatenate a Boolean value to a string, which is not a supported operation.
You could do
print w + str(e)
and that would be functional.
Upvotes: 3