Natural Language Processing · Beginner level

Beginner level · Module 2: Understanding Text and Language Data · Lesson 1 of 3

Characters, Encodings and Text Files

Learners see how computers store text as numbers, why UTF-8 is the safe default and how encoding mistakes produce garbled characters.

In this lesson you will

  • Explain characters and encodings
  • Read and write text files safely in UTF-8

Key concepts

characterUnicodeUTF-8encoding errorsopen(..., encoding='utf-8')

The lesson

Computers store each character as a number. Unicode gives every character in every writing system its own number, and UTF-8 is the most common way to store those numbers in files. Arabic script, accented letters and symbols used in some South Sudanese orthographies all need Unicode to display correctly.

When a file is saved in one encoding and opened in another, characters become garbled (for example 'é' instead of 'é'). The safe habit is to read and write text with encoding='utf-8' and to check a sample of the text after loading.

In Python, a string is a sequence of characters. len('Juba') is 4, and 'Juba'.lower() returns 'juba'. These simple operations are the building blocks of everything that follows.

Step by step

  1. Open a notebook in Jupyter or Colab.
  2. Write a short multilingual text to a file with open('notes.txt', 'w', encoding='utf-8').
  3. Read it back and print its length and first 50 characters.
  4. Open the same file with a wrong encoding (latin-1) and describe what goes wrong.

Practice activity

Save, reload and inspect a text file containing English and Arabic-script text, and document what happens with a wrong encoding.

Expected result: A notebook that round-trips the text correctly in UTF-8 and shows the garbling caused by a wrong encoding.

Check your understanding

  1. What does UTF-8 do?

    Show answer

    It stores Unicode characters as bytes in a file, so text in any writing system can be saved and read.

  2. What causes garbled characters like 'é'?

    Show answer

    Reading text with a different encoding from the one used to save it.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.