unicode
python
string-handling
text-processing
utf-8

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.

python
1# The raw bytes of a UTF-8 BOM
2bom_bytes = b'\xef\xbb\xbf'
3print(bom_bytes.decode('utf-8'))       # Prints nothing visible
4print(repr(bom_bytes.decode('utf-8'))) # '\ufeff'

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.

python
1# Simulating a file with BOM
2text = "name,age,city"
3
4# This comparison fails because the first character is not 'n'
5print(text == "name,age,city")        # False
6print(text.startswith("name"))        # False
7print(repr(text[0]))                  # '\ufeff'
8print(len(text))                      # 14, not 13

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.

python
1# Writing a file with BOM (simulating what Excel or Notepad produces)
2from pathlib import Path
3
4test_file = Path("data.csv")
5test_file.write_bytes(b"\xef\xbb\xbfname,age\nAlice,30\nBob,25\n")
6
7# BAD: Reading with utf-8 preserves the BOM
8with open(test_file, "r", encoding="utf-8") as f:
9    header = f.readline().strip()
10print(repr(header))  # '\ufeffname,age'
11
12# GOOD: Reading with utf-8-sig removes the BOM
13with open(test_file, "r", encoding="utf-8-sig") as f:
14    header = f.readline().strip()
15print(repr(header))  # 'name,age'

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:

python
1def strip_bom(text: str) -> str:
2    """Remove leading BOM if present."""
3    if text.startswith(""):
4        return text[1:]
5    return text
6
7# Usage
8raw = "id,name,email"
9clean = strip_bom(raw)
10print(repr(clean))  # 'id,name,email'

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:

python
1import csv
2from pathlib import Path
3
4def read_csv_safe(filepath: str) -> list[dict]:
5    """Read a CSV file, handling BOM transparently."""
6    with open(filepath, "r", encoding="utf-8-sig", newline="") as f:
7        reader = csv.DictReader(f)
8        return list(reader)
9
10# Works regardless of whether the file has BOM
11rows = read_csv_safe("export.csv")
12for row in rows:
13    print(row["name"], row["age"])

With pandas, read_csv takes an encoding parameter:

python
1import pandas as pd
2
3# Option 1: Use utf-8-sig encoding
4df = pd.read_csv("export.csv", encoding="utf-8-sig")
5
6# Option 2: If the file is already loaded with BOM in headers
7df = pd.read_csv("export.csv", encoding="utf-8")
8df.columns = [col.lstrip("") for col in df.columns]

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:

python
1import json
2
3# Bytes with BOM
4raw_bytes = b'\xef\xbb\xbf{"key": "value"}'
5
6# json.loads accepts BOM-prefixed bytes but rejects a str that starts with a BOM
7text = raw_bytes.decode("utf-8-sig")
8data = json.loads(text)
9print(data)  # {'key': 'value'}

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:

python
1from pathlib import Path
2
3def has_bom(filepath: str) -> bool:
4    """Check if a file starts with UTF-8 BOM."""
5    with open(filepath, "rb") as f:
6        return f.read(3) == b"\xef\xbb\xbf"
7
8# Check multiple files
9for path in Path(".").glob("*.csv"):
10    if has_bom(str(path)):
11        print(f"BOM detected: {path}")

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:

python
1from pathlib import Path
2
3def remove_bom_from_file(filepath: str) -> bool:
4    """Remove UTF-8 BOM from a file if present. Returns True if BOM was removed."""
5    path = Path(filepath)
6    content = path.read_bytes()
7    if content.startswith(b"\xef\xbb\xbf"):
8        path.write_bytes(content[3:])
9        return True
10    return False

From the command line:

bash
1# Check for BOM
2hexdump -C data.csv | head -1
3# If BOM is present, the first three bytes will be: ef bb bf
4
5# Remove BOM using sed (macOS)
6sed -i '' '1s/^\xef\xbb\xbf//' data.csv
7
8# Remove BOM using sed (Linux)
9sed -i '1s/^\xef\xbb\xbf//' data.csv

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:

python
1import csv
2
3# Writing WITH BOM (for Excel compatibility)
4with open("for_excel.csv", "w", encoding="utf-8-sig", newline="") as f:
5    writer = csv.writer(f)
6    writer.writerow(["name", "city"])
7    writer.writerow(["Alice", "Tokyo"])
8
9# Writing WITHOUT BOM (standard UTF-8)
10with open("for_api.csv", "w", encoding="utf-8", newline="") as f:
11    writer = csv.writer(f)
12    writer.writerow(["name", "city"])
13    writer.writerow(["Alice", "Tokyo"])

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.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design