How to get ° character in a string in python?

前端 未结 6 1084
南方客
南方客 2020-12-07 16:07

How can I get a ° (degree) character into a string?

6条回答
  •  醉话见心
    2020-12-07 16:43

    Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.

    The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters ┬░ instead of a degree °.

    Demonstration (using python 2.7 in a windows console):

    deg = u'\xb0`  # utf code for degree
    print deg.encode('utf8')
    

    effectively outputs ┬░.

    Fix: just force the correct encoding (or better use unicode):

    local_encoding = 'cp850'    # adapt for other encodings
    deg = u'\xb0'.encode(local_encoding)
    print deg
    

    or if you use a source file that explicitely defines an encoding:

    # -*- coding: utf-8 -*-
    local_encoding = 'cp850'  # adapt for other encodings
    print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)
    

提交回复
热议问题