Python2和Python3中的差异

95 阅读1分钟

编码

chinese_str = "你好,世界!"  # 使用 Unicode 编码创建中文字符串  
english_str = "Hello, world!"  # 使用 Unicode 编码创建英文字符串  
# 编码 Unicode 字符串为 UTF-8 字节串  
utf8_str = chinese_str.encode("utf-8")

# 解码 UTF-8 字节串为 Unicode 字符串  
decoded_utf8_str = utf8_str.decode("utf-8")  
# 获取字符串长度  
length = len(chinese_str)#每个unicode符号的长总和

# 拆分字符串  
words = chinese_str.split(" ")

# 替换字符串中的某个字符  
modified_str = chinese_str.replace("好", "坏")
# Python3  
with open("chinese_words.txt", "r", encoding="utf-8") as f:  
    content = f.read()  


# -- coding: utf-8 --
chinese_str = u"你好,世界!"  
utf8_str = chinese_str.encode("utf-8")  
length = len(chinese_str)#字节数
decoded_utf8_str = utf8_str.decode("utf-8")  
with open("chinese_words.txt", "r", encoding="utf-8") as f:  
    content = f.read()  


Python3 更倾向于使用 Unicode 编码,而在 Python2 中,需要明确指定编码方式。在 Python3 中,编码和解码操作相对较少,而在 Python2 中,需要更多地进行编码和解码处理。同时,Python3 中字符串长度是指 Unicode 字符数量,而 Python2 中是指字节长度。在文件操作方面,Python3 更加强调使用 UTF-8 编码。

其他

print(chinese_str)

name = "张三"  
age = 25
words = ["Hello", "World", "Python3"]  
result = " ".join(words)  
print(result)  # 输出:Hello World Python3  

name = "张三"  
age = 25  
result = f"我的名字是{name},我{age}岁了。"  
print(result)  

# 使用字符串占位符  
result = "我的名字是 {0},我 {1} 岁了。".format(name, age)  
print(result)  
name = "张三"  
age = 25
print chinese_str

name = "张三"  
age = 25
words = ["Hello", "World", "Python3"]  
result = " ".join(words)  
print(result)  # 输出:Hello World Python3  

# 使用字符串占位符  
result = "我的名字是 %s,我 %s 岁了。" % (name, age)  
print(result)