【问题标题】:Help me make my Python 2 code work in Python 3帮助我让我的 Python 2 代码在 Python 3 中工作
【发布时间】:2011-08-03 00:58:27
【问题描述】:
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,我将不胜感激。谢谢。

【问题讨论】:

  • 这是为了代码高尔夫挑战吗?
  • 我认为你只是有编码问题(非 ascii 字符)

标签: python python-3.x python-2.x


【解决方案1】:

我将您的代码粘贴到一个文件中,保存它,然后在 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'

这就是为什么您的代码会产生 SyntaxErrors。

只需重新输入(或复制下面的代码),它将在 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

【讨论】:

  • 你赢得了互联网。谢谢你先生。
【解决方案2】:

这些问题与您的 Python 版本无关。你的代码中有奇怪的字符。

我将它粘贴到Metapad 中,然后出现了一堆?,我认为是不可打印的字符。

只需重新输入它就可以正常工作,或者找到一个可以显示这些字符并删除它们的文本编辑器,或者使用 Python 删除任何不可打印的字符。

【讨论】:

    【解决方案3】:

    确实,@agf 是正确的。第一个(__) 的下划线之间有一个奇怪的字符。已更正(在 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
    

    【讨论】:

      【解决方案4】:

      在您的 python 安装中使用 2to3。它是 2.7.2+ 的标准(我认为)

      【讨论】:

      • 我现在正在使用 Python 3.1,但我无法找到它。你知道它具体在哪个目录吗?
      • @Joe Mas:它安装在您的 Python 安装中,位于 Tools\Scripts 下。在 Unix 上它也作为单独的命令安装,所以你只需运行 2to3,但在 Windows 下我认为你必须运行 python3 C:\WhereEverYourPythonIs\Tools\Scripts\2to3.py,但这可能在以后的版本中有所改变。
      • 查看docs.python.org/library/2to3.html 的文档。这样就不会那么混乱了。
      猜你喜欢
      • 2018-08-11
      • 1970-01-01
      • 2015-03-31
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多