Skip to main content
 首页 » 编程设计

python之帮助我使我的 Python 2 代码在 Python 3 中工作

2025年05月04日20qq78292959

import math,sys,time;i=0 
while 1: sys.stdout.write("\r"+':(_​_)'[:3+int(round(math.sin(​i)))]+'n'+':(__)'[3+int(ro​und(math.sin(i))):]);sys.s​tdout.flush();time.sleep(.​15);i+=0.5*math.pi 

我很久以前用 Python 2 编写了那个简单的程序,它运行良好,但在 Python 3 中有语法错误。如果有人可以帮助我将它更新为 Python 3 兼容,我将不胜感激。谢谢。

请您参考如下方法:

我将你的代码粘贴到一个文件中,保存它,然后在 Python shell 中打开它:

In [10]: f=open('test2.py') 
 
In [11]: content=f.read() 
 
In [12]: content 
Out[12]: '#!/usr/bin/env python\n# coding: utf-8\n\nimport math,sys,time;i=0\nwhile 1: sys.stdout.write("\\r"+\':(_\xe2\x80\x8b_)\'[:3+int(round(math.sin(\xe2\x80\x8bi)))]+\'n\'+\':(__)\'[3+int(ro\xe2\x80\x8bund(math.sin(i))):]);sys.s\xe2\x80\x8btdout.flush();time.sleep(.\xe2\x80\x8b15);i+=0.5*math.pi\n' 

注意散布在各处的 '\xe2\x80\x8b' 字节。这些是用 utf-8 编码的 ZERO WIDTH SPACE 字符:

In [24]: print(repr(u'\N{ZERO WIDTH SPACE}'.encode('utf-8'))) 
'\xe2\x80\x8b' 

这就是您的代码导致语法错误的原因。

只需重新输入(或复制下面的代码),它将在 Python3 中运行:

import math, sys, time; i=0 
while 1: sys.stdout.write('\r'+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]); sys.stdout.flush(); time.sleep(0.15); i+=0.5*math.pi