How to set UTF-8 in Python?

QuestionsQuestions8 SkillsProYour First Linux LabOct, 09 2025
0397

To set UTF-8 encoding in Python, you can follow these steps:

  1. Specify Encoding in Source Files:
    If you're using Python 2, you can specify the encoding at the top of your Python file by adding the following line:

    # -*- coding: utf-8 -*-

    In Python 3, UTF-8 is the default encoding for source files, so you typically don't need to specify it.

  2. Reading and Writing Files:
    When reading from or writing to files, you can specify the encoding explicitly. For example:

    # Writing to a file with UTF-8 encoding
    with open('example.txt', 'w', encoding='utf-8') as f:
        f.write("Привет, мир!")
    
    # Reading from a file with UTF-8 encoding
    with open('example.txt', 'r', encoding='utf-8') as f:
        content = f.read()
        print(content)
  3. Setting the Locale (if necessary):
    If you're dealing with terminal output and want to ensure that your terminal supports UTF-8, you can set the locale in your script:

    import locale
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  4. Using UTF-8 in Strings:
    In Python 3, all string literals are Unicode by default, so you can directly use UTF-8 characters in your strings:

    print("Привет, мир!")

By following these steps, you can effectively work with UTF-8 encoding in Python.

0 Comments

no data
Be the first to share your comment!