What is \ufeff in a Python string and how to remove it
Codemia Knowledge Hub ·
The \ufeff character at the start of a Python string is a Byte Order Mark (BOM). It shows up when a file saved as "UTF-8 with BOM" is decoded with the plain utf-8 codec instead of utf-8-sig. Open the file with encoding="utf-8-sig" and the BOM is stripped automatically. If the string is already loaded, remove the leading \ufeff before processing it.
What the Byte Order Mark is
The BOM (U+FEFF) was designed to signal the byte order of a text stream. In UTF-16 and UTF-32, multi-byte units can be stored big-endian or little-endian, and a BOM at the start tells the decoder which order to expect.
UTF-8 has no byte order problem, but some tools still prepend a BOM as a signature that the file is UTF-8. Microsoft Notepad, Excel's CSV export and many Windows applications do this by default.
In UTF-8 the BOM is the three bytes EF BB BF. Decoded with the utf-8 codec, they become the single character U+FEFF in the string.
Why the BOM breaks comparisons and lookups
The BOM is invisible in most displays, but it is a real character. It breaks string comparisons, dictionary key lookups, CSV header parsing and JSON processing.
In CSV files the BOM becomes part of the first column header. A column named \ufeffname does not match "name" in a dictionary lookup, so you get a KeyError that is hard to debug because the header looks correct when printed.
Fix 1: read files with utf-8-sig
The utf-8-sig codec strips a leading BOM during decoding and is otherwise identical to utf-8. If there is no BOM, it behaves exactly like utf-8.
This is the cleanest fix. Use utf-8-sig where the file is first opened, and all downstream code gets clean text.
Fix 2: strip the BOM from an in-memory string
When text arrives from an API, message queue or database and you cannot control the encoding parameter, strip the BOM afterwards:
Strip only from the start of the string. A global .replace() of U+FEFF can corrupt data, because U+FEFF also works as a zero-width no-break space inside text (its secondary Unicode function).
Fix 3: CSV files from Excel
Excel exports are among the most common sources of BOM problems. A robust reading pattern:
With pandas, read_csv takes an encoding parameter:
Fix 4: JSON input
A BOM makes json.loads fail when the input is a str. It raises JSONDecodeError: Unexpected UTF-8 BOM. BOM-prefixed bytes are accepted:
The safest approach is to decode bytes with utf-8-sig before passing the string to json.loads.
Detecting a BOM in a file
To check a file before deciding how to process it:
This helps in data pipelines where files come from several sources with inconsistent encoding.
Removing the BOM from files on disk
To remove the BOM permanently:
From the command line:
Writing files with or without a BOM
Some consumers need the BOM, for example Excel reading UTF-8 CSV files correctly on Windows. utf-8-sig also works for writing and prepends the BOM bytes:
Mistakes that bring the BOM back
Replacing U+FEFF globally. This removes every occurrence, not just the leading BOM. Because U+FEFF is also a zero-width no-break space, it can legitimately appear inside text. Strip only the leading character.
Decoding bytes twice. If bytes pass through two decoding steps with different codecs, hidden characters can reappear. Decode once at the boundary and work with strings from then on.
Assuming the BOM only appears in files. Clipboard data, HTTP response bodies, database exports and API payloads can all contain one. Treat any text crossing a system boundary as possibly BOM-prefixed.
Leaving the BOM out of test fixtures. Developers usually create clean UTF-8 files, so BOM bugs stay hidden in development. Add at least one fixture that starts with b"\xef\xbb\xbf" to catch regressions in CSV, JSON and config file parsers.
Forgetting newline="" with the csv module. Always pass newline="" when opening files for csv to prevent double newline translation. This is unrelated to the BOM but often shows up in the same CSV bugs.
Related reading
- Variation in BLEU \`Score\`
- Visualize Gensim Word2vec Embeddings in Tensorboard Projector
- Vocabulary Processor function
- what actually word embedding dimensions values represent?
- ValueError Argument must be a dense tensor - Python and TensorFlow
- ValueError Can't convert non-rectangular Python sequence to Tensor
- What algorithm can you use to find duplicate phrases in a string?
- What algorithm gives suggestions in a spell checker?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.