0

I need to display "Δ return" in a report generated by Python 2.7. However, below error when print. How to make it work?

print u"Δ"
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in position 8: ordinal not in range(128)

print u"Δ".encode('utf-8')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in position 2: ordinal not in range(128)

print u"Δ".decode('utf-8')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in position 2: ordinal not in range(128)

These are methods suggested in How do I write a capital Greek "delta" as a string in Python 2.7?

Eb946207
  • 748
  • 8
  • 26
Lisa
  • 4,126
  • 12
  • 42
  • 71
  • Your terminal probably is set to ascii. – juanpa.arrivillaga Dec 31 '18 at 17:57
  • See this https://pythonforundergradengineers.com/unicode-characters-in-python.html – Sagar P. Ghagare Dec 31 '18 at 18:00
  • First one is correct. Second one should work too. Third one is wrong. If the first one doesn't work, then your terminal emulator is not configured properly. Voting to close as not reproducible. – wim Dec 31 '18 at 18:00
  • @juanpa.arrivillaga could you explain a bit more why terminal setting affects how python's `print` operates? – erik258 Dec 31 '18 at 18:01
  • 1
    Use python 3, and this well be fixed! – Eb946207 Dec 31 '18 at 18:02
  • There is some relevant information here: [Setting the correct encoding when piping stdout in Python](https://stackoverflow.com/q/492483/674039). Skip the accepted answer, which is bad/wrong, and look to the most upvoted answer. – wim Dec 31 '18 at 18:06
  • 1
    @EthanK Not necessarily, if locale or env like LC_CTYPE is set to ascii and terminal misconfigured. Same things could happen in Python 3. – wim Dec 31 '18 at 18:08
  • @wim Fine... but use Python 3 anyway! – Eb946207 Dec 31 '18 at 18:09
  • 2
    Some people have to work with legacy code bases that are in Python 2.7 and there is not sufficient business justification to rewrite/update them to Python 3. Anyway in this case it is not a problem of the Python version in the first place, so your comment is not too helpful :) – wim Dec 31 '18 at 18:13
  • With python3 you can just `print ("Δ")` – Pedro Lobito Dec 31 '18 at 18:15
  • Would `u'\u0394'` instead of `u'Δ'` work? – JosefZ Jan 13 '21 at 17:02

0 Answers0