简体   繁体   中英

% vs. + as related to strings in Python?

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?

%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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM