Znak Unicode U+FEFF
jest znacznikiem kolejności bajtów lub BOM i służy do odróżnienia dużego i małego endianowania kodowania UTF-16. Jeśli odszyfrujesz stronę przy użyciu właściwego kodera-dekodera, Python ją usunie. Przykłady:
#!python2
#coding: utf8
u = u'ABC'
e8 = u.encode('utf-8') # encode without BOM
e8s = u.encode('utf-8-sig') # encode with BOM
e16 = u.encode('utf-16') # encode with BOM
e16le = u.encode('utf-16le') # encode without BOM
e16be = u.encode('utf-16be') # encode without BOM
print 'utf-8 %r' % e8
print 'utf-8-sig %r' % e8s
print 'utf-16 %r' % e16
print 'utf-16le %r' % e16le
print 'utf-16be %r' % e16be
print
print 'utf-8 w/ BOM decoded with utf-8 %r' % e8s.decode('utf-8')
print 'utf-8 w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig')
print 'utf-16 w/ BOM decoded with utf-16 %r' % e16.decode('utf-16')
print 'utf-16 w/ BOM decoded with utf-16le %r' % e16.decode('utf-16le')
Należy pamiętać, że EF BB BF
jest BOMem kodowanym w UTF-8. Nie jest wymagany w przypadku UTF-8, ale służy tylko jako podpis (zazwyczaj w systemie Windows).
wyjściowa:
utf-8 'ABC'
utf-8-sig '\xef\xbb\xbfABC'
utf-16 '\xff\xfeA\x00B\x00C\x00' # Adds BOM and encodes using native processor endian-ness.
utf-16le 'A\x00B\x00C\x00'
utf-16be '\x00A\x00B\x00C'
utf-8 w/ BOM decoded with utf-8 u'\ufeffABC' # doesn't remove BOM if present.
utf-8 w/ BOM decoded with utf-8-sig u'ABC' # removes BOM if present.
utf-16 w/ BOM decoded with utf-16 u'ABC' # *requires* BOM to be present.
utf-16 w/ BOM decoded with utf-16le u'\ufeffABC' # doesn't remove BOM if present.
Zauważ, że utf-16
kodowane wymaga BOM może być obecny, lub Python nie będą wiedzieć, czy dane są big- lub little-endian.
Skąd pochodzą te dane wejściowe? Co próbujesz zrobić? Proszę podać swój kod Pythona. –
Nawiasem mówiąc, uważam, że .replace() działa we współczesnym pythonie, jeśli pamiętam wskaźnik Unicode: s.replace (u '\ ufeff', '') –
@DougBradshaw kiedy mówisz "nowoczesny python", masz na myśli 2,7+ lub 3,0+? – teewuane