2014-01-31 170 views
1

我是Python的新手,并且正在从工作中解读一些代码。Python:.encode('ascii','ignore')做什么?

我注意到有很多行包含row[0].encode('ascii', 'ignore')

我做了一些阅读,它似乎是从unicode转换为字节。

它只是一种方法来将字符串从u'string'转换为字符串?

+2

这个问题似乎是题外话,因为它很容易解决通过阅读文档 – mhlester

回答

2
 
    encode(...) 
     S.encode([encoding[,errors]]) -> object 

     Encodes S using the codec registered for encoding. encoding defaults 
     to the default encoding. errors may be given to set a different error 
     handling scheme. Default is 'strict' meaning that encoding errors raise 
     a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 
     'xmlcharrefreplace' as well as any other name registered with 
     codecs.register_error that is able to handle UnicodeEncodeErrors. 

所以它编码一个unicode字符串ASCII和忽略错误

>>> "hello\xffworld".encode("ascii") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character '\xff' in position 5: ordinal not in range(128) 

VS

>>> "hello\xffworld".encode("ascii", "ignore") 
b'helloworld' 
+0

所以如果我有一个字符串S的形式u'string'将S.encode('ascii','忽略')将S转换为“字符串”?如果我以前在unicode中有S,如果我想检查内部字符串,我可以检查S == u'string'吗?或者我如何检查平等? – SeekingAlpha

+0

@SeekingAlpha,如果unicode字符串完全是ASCII字符,它会给你那些字节。任何不是ASCII的将被过滤掉 –