You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

设置Python编码以解决中文打印乱码及多变量显示异常问题

Hey there! Let's break down what's happening here and fix your Chinese character printing issue in Python 2.

Why This Happens

In Python 2, the print statement behaves differently when you pass multiple arguments versus a single one:

  • When you run print(rows[0]) or print(rows[1]), Python calls str() on the single string, which handles UTF-8 encoding properly and outputs readable characters.
  • But when you pass multiple arguments like print(rows[0], rows[1]), Python wraps them into a tuple and outputs the repr() of that tuple. That's why you see those \xe5\xb7\xb2 escape sequences instead of Chinese text—repr() is designed to show a machine-readable version of objects, not human-readable content.

Also, notice the garbled character 宸� in your rows definition: this usually means your source file wasn't saved in UTF-8 encoding, even though you added the # -*- coding: utf-8 -*- header. Double-check your editor's save settings to ensure the file uses UTF-8.

Fixes You Can Apply

1. Use String Formatting or Concatenation

Instead of passing multiple arguments to print, combine your values into a single string first. This forces Python to use str() instead of repr() for output:

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# Fix the garbled string first (ensure file is saved as UTF-8)
rows = ('已', '已经激活的区域语言')

# Option 1: String formatting (cleanest)
print(u"{} {}".format(rows[0], rows[1]))
# Option 2: String concatenation
print(rows[0] + ' ' + rows[1])
# For mixing strings and numbers
print(u"{} {}".format(rows[0], 1))

2. Switch to Python 3 (Highly Recommended)

Python 2 is no longer supported, and Python 3's print() function handles multiple arguments correctly by default—it joins values with spaces and outputs human-readable text, not repr. Your code would work as expected with almost no changes:

# No need for reload(sys) or setdefaultencoding in Python 3
rows = ('已', '已经激活的区域语言')
print(rows[0])
print(rows[1])
print(rows[0], rows[1])  # Prints readable Chinese now
print(rows[0], 1)        # Works for mixed types too

3. Fix the Garbled Character

Ensure your .py file is saved with UTF-8 encoding (most code editors let you set this in the "Save As" menu or settings). The 宸� in your original code is evidence that the string wasn't encoded correctly during saving.

Sample Fixed Output (Python 2 with Option 1)

已
已经激活的区域语言
已 已经激活的区域语言
已 已经激活的区域语言
已 1

内容的提问来源于stack exchange,提问作者Kwang Hun Lee

火山引擎 最新活动