0

Not sure what I'm doing wrong here, but with this:

# -*- coding: utf-8 -*-

class Foo(object):
    CURRENCY_SYMBOL_MAP = {"CAD":'$', "USD":'$', "GBP" : "£"}

    def bar(self, value, symbol="GBP"):
        result = u"%s%s" % (self.CURRENCY_SYMBOL_MAP[symbol], value)
        return result

if __name__ == "__main__":
    f = Foo()
    print f.bar(unicode("19.00"))

I get:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print f.bar(unicode("19.00"))
  File "test.py", line 7, in bar
    result = u"%s%s" % (self.CURRENCY_SYMBOL_MAP[symbol], value)
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

This is with Python 2.7.6

PS - I get that there are libraries like Babel for formmatting things as currency, my question is more with respect to unicode strings and the % operator.

1

2 Answers 2

3

Make sure the strings you're inserting are Unicode too.

CURRENCY_SYMBOL_MAP = {"CAD":u'$', "USD":u'$', "GBP" : u"£"}
Sign up to request clarification or add additional context in comments.

Comments

1

You are attempting to insert a non-unicode string into a unicode string. You just have to make the values in CURRENCY_SYMBOL_MAP unicode objects.

# -*- coding: utf-8 -*-

class Foo(object):
    CURRENCY_SYMBOL_MAP = {"CAD":u'$', "USD":u'$', "GBP" : u"£"}  # this line is the difference

    def bar(self, value, symbol="GBP"):
        result = u"%s%s" % (self.CURRENCY_SYMBOL_MAP[symbol], value)
        return result

if __name__ == "__main__":
    f = Foo()
    print f.bar(unicode("19.00"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.