开发者

Help me make my Python 2 code work in Python 3

开发者 https://www.devze.com 2023-03-24 14:38 出处:网络
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.p
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

I wrote that simple program in Python 2 a long time ago and it worked fine but it has syntax errors in Python 3. I would greatly appreciate if someo开发者_如何转开发ne could help me update it to be Python 3 compliant. Thanks.


I pasted your code in a file, saved it, then opened it in a 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'

Notice the '\xe2\x80\x8b' bytes sprinkled here and there. These are ZERO WIDTH SPACE characters encoded in utf-8:

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

This is why your code is giving rise to SyntaxErrors.

Just retype it (or copy the code below) and it will run in 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


The problems has nothing to do with your Python version. You've got weird characters in your code.

I pasted it in Metapad and a bunch of ? showed up, I assume meaning unprintable character.

Just retype it and it will work fine, or find a text editor which will show those characters and delete them, or use Python to delete any non-printable characters.


Indeed, @agf is correct. There was a weird character between the underscores in the first (__). Corrected (and works fine with Python 3):

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(.15);i+=0.5*math.pi


Use 2to3 on your python installation. It comes standard (I think) with 2.7.2+

0

精彩评论

暂无评论...
验证码 换一张
取 消