2012-06-30 47 views
1

當使用unicode_literals時,使用pygame.Color名稱的正確方法是什麼?如何使用unicode_literals引用pygame顏色?

Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import pygame 
>>> pygame.ver 
'1.9.2pre' 
>>> pygame.Color('red') 
(255, 0, 0, 255) 
>>> from __future__ import unicode_literals 
>>> pygame.Color('red') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: invalid argument 

回答

1

unicode_literals被啓用,Python 2中解釋字符串文字的方式的Python 3。即相同,'red'是Unicode字符串(在Python 2稱爲unicodestr在3)中,並b'red'是一個字節串(在Python 3中稱爲strbytes,Python 3中稱爲bytes)。

由於pygame.Color只接受一個字節字符串,把它傳遞b'red'

 
>>> from __future__ import unicode_literals 
>>> pygame.Color('red') 
Traceback (most recent call last): 
    File "", line 1, in 
ValueError: invalid argument 
>>> pygame.Color(b'red') 
(255, 0, 0, 255) 
1
>>> type('red') 
str 

>>> from __future__ import unicode_literals 

>>> type('red') 
unicode 

>>> type(str('red')) 
str 

>>> import pygame 

>>> pygame.ver 
'1.9.1release' 

>>> pygame.Color(str('red')) 
(255, 0, 0, 255)