在Python中定义中文通常有以下几种方法:
直接使用中文字符
-*- coding: utf-8 -*-
print("你好,世界!")
使用Unicode转义序列
print("\u4f60\u597d\uff0c\u4e16\u754c\uff01")
使用中文字符串变量
-*- coding: utf-8 -*-
chinese_str = "你好,世界!"
print(chinese_str)
设置语言环境
import locale
locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
设置字符编码
import sys
sys.setdefaultencoding('utf-8')
在文件开头添加编码声明
-*- coding: utf-8 -*-
使用`u`前缀
str1 = u"你好,世界!"
print(str1)
使用`open`函数指定编码
with open("file.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
请确保在代码文件开头指定编码方式,例如` -*- coding: utf-8 -*-`,以确保Python解释器正确解析中文字符。