[Python-Dev] Format strings, Unicode, and Py2.7: need clarification (original) (raw)

Hobson Lane hobsonlane at gmail.com
Thu May 18 01:14:47 EDT 2017


Because .format() is a method on an instantiated str object in e and so must return the same type so additional str methods could be stacked on after it, like .format(u'hi').decode(). Whereas the % string interpolation is a binary operation, so, like addition, where the more general type can be used for the return value, analogous to 1 + 2.0 returning a float.

--Hobson (503) 974-6274 gh <https://github.com/hobson/> twtr <https://twitter.com/hobsonlane> li <https://www.linkedin.com/in/hobsonlane> g+ <http://plus.google.com/+HobsonLane/> so <http://stackoverflow.com/users/623735/hobs>

On Wed, May 17, 2017 at 2:41 PM, Craig Rodrigues <rodrigc at crodrigues.org> wrote:

Hi,

While cleaning up some code during Python 2 -> Python 3 porting, I switched some code to use str.format(), I found this behavor: Python 2.7 ========= a = "%s" % "hi" b = "%s" % u"hi" c = u"%s" % "hi" d = "{}".format("hi") e = "{}".format(u"hi") f = u"{}".format("hi") type(a) == str type(b) == unicode type(c) == unicode type(d) == str type(e) == str type(f) == unicode My intuition would lead me to believe that type(b) and type(e) would be the same (unicode), but they are not. The confusion for me is why is type(e) of type str, and not unicode? Can someone clarify this for me? I understand that in Python 3, all these cases are str, so it is not as big a problem there, but I am trying to keep things working on Python 2.7. Thanks. -- Craig


Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/ hobsonlane%40gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20170517/c1d0351b/attachment.html>



More information about the Python-Dev mailing list