2010-07-09 126 views

回答

27

把這一行在源代碼的頂部

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

如果你的編輯器使用不同的編碼,代替UTF-8

然後你就可以直接在源

+0

假設您的編輯器使用UTF-8。如果您的編輯器使用不同的字符集,則請改爲指明。 – 2010-07-09 19:19:12

+0

# - * - 編碼:cp1252 - * - 是爲我工作的 – Richard 2010-07-15 13:48:40

27
>>> u"\u00b0" 
u'\xb0' 
>>> print _ 
° 

順便說一句,我所做的一切都是在Google上搜索「unicode學位」。這帶來了兩個結果: 「度SIGN U + 00B0」 和 「攝氏度U + 2103」,這實際上是不同的:

>>> u"\u2103" 
u'\u2103' 
>>> print _ 
℃ 
+0

或者Python 3中的'a ='\ u00b0''。 – JAB 2010-07-09 17:42:47

+7

@JAB:或者只是'a ='°''。 – SilentGhost 2010-07-09 17:46:36

+0

@SilentGhost:好的,但是我不記得°的數字鍵盤代碼,並且不想在當時查看它。 – JAB 2010-07-09 18:30:40

50

這是最coder-包括UTF-8字符友好的版本指定Unicode字符:

degree_sign= u'\N{DEGREE SIGN}' 

注意:必須大寫字母N在\N結構,以避免與「\ n」換行符混亂。花括號內的字符名稱可以是任何情況。

記住一個字符的name比它的unicode索引更容易記住。它也更易讀,易於調試。該字符替換髮生在編譯時間爲:.py[co]文件將包含一個常數u'°'

>>> import dis 
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval') 
>>> dis.dis(c) 
    1   0 LOAD_CONST    0 (u'\xb0') 
       3 RETURN_VALUE 
>>> c.co_consts 
(u'\xb0',) 
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval') 
>>> c.co_consts 
(u'\xb0-\u2205',) 
>>> print c.co_consts[0] 
°-∅ 
6

只使用\xb0 (in a string);蟒蛇會把它轉換成自動

6

以上答案假設UTF8編碼可安全使用 - 這一個專門針對Windows。

Windows控制檯normaly使用CP850編碼和 UTF8,因此,如果您嘗試使用源文件UTF8編碼,你讓那些2(不正確)的字符┬░代替程度°

示範(在Windows控制檯使用python 2.7):

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

有效輸出┬░

修復:正義的力量正確的編碼(或更好地使用Unicode):

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

,或者如果您使用的是明確地定義編碼源文件:

# -*- 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) 
相關問題