string manipulation
utf-8 encoding
data cleaning
python
text processing

Remove non-UTF-8 characters from a string in Python

Codemia Knowledge Hub ·

In Python, the simplest way to remove characters that cannot be encoded as UTF-8 is text.encode('utf-8', 'ignore').decode('utf-8'). The 'ignore' error handler drops anything invalid. A regular expression that keeps only matching patterns is an alternative. Either way the operation is lossy, so make sure you are not discarding data you need.

Why UTF-8 is the target encoding

A character encoding maps each character (letters, digits, symbols) to an integer so text can be stored and transmitted. UTF-8 can represent every Unicode character using one to four bytes, and it is the standard on the web and in many programming environments:

  • Compatibility: UTF-8 is backward compatible with ASCII.
  • Efficiency: for mostly ASCII text, it uses less storage than UTF-16 or UTF-32.
  • Universality: it supports all Unicode characters, so it handles multilingual text.

Where non-UTF-8 characters come from

They usually come from misconfigured input sources, legacy data systems, or file corruption. They can raise encoding exceptions or break data pipelines.

Removing them with encode and decode

python
1def remove_non_utf8_symbols(text):
2    # 'ignore' drops characters that cannot be encoded as UTF-8
3    return text.encode('utf-8', 'ignore').decode('utf-8')
4
5# Example usage:
6sample_text = "This is a test string with a non-UTF-8 symbol: \ud83d"
7cleaned_text = remove_non_utf8_symbols(sample_text)
8print(cleaned_text)  # Output: This is a test string with a non-UTF-8 symbol:

With 'ignore', characters that cannot be encoded are dropped rather than replaced, as the output shows.

Removing them with a regular expression

In a Python str, the characters UTF-8 cannot encode are lone surrogates (\ud800 to \udfff). A regular expression can match that range and remove it:

python
1import re
2
3def regex_remove_non_utf8(text):
4    return re.sub(r'[\ud800-\udfff]', '', text)
5
6# Example usage:
7cleaned_text = regex_remove_non_utf8(sample_text)
8print(cleaned_text)  # Output: Same as 'remove_non_utf8_symbols'

Before you strip characters

  • Consider converting instead of removing. Depending on how the strings are used, converting the content to valid UTF-8 may be better than deleting it.
  • Expect data loss. Removal discards part of the original content, so check that nothing important is thrown away.
AspectDescription
UTF-8 AdvantagesCompatibility with ASCII, efficiency for mainly ASCII texts, universal character representation.
Common IssuesMisconfigured input sources, legacy systems, data corruption.
Python MethodUse encode and decode methods to cleanse non-UTF-8 characters.
Regex MethodApply regular expressions to identify and extract valid UTF-8 patterns.
ConsiderationsChoose approaches based on application requirements; be mindful of potential data loss.

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