【发布时间】:2012-02-26 12:49:40
【问题描述】:
我目前正在通过 python 挑战,我已经达到 4 级,see here 我才学习 python 几个月,我正在尝试学习 python 3 超过 2.x 所以到目前为止一切顺利,除了我使用这段代码时,这里是 python 2.x 版本:
import urllib, re
prefix = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
findnothing = re.compile(r"nothing is (\d+)").search
nothing = '12345'
while True:
text = urllib.urlopen(prefix + nothing).read()
print text
match = findnothing(text)
if match:
nothing = match.group(1)
print " going to", nothing
else:
break
所以要将其转换为 3,我将更改为:
import urllib.request, urllib.parse, urllib.error, re
prefix = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
findnothing = re.compile(r"nothing is (\d+)").search
nothing = '12345'
while True:
text = urllib.request.urlopen(prefix + nothing).read()
print(text)
match = findnothing(text)
if match:
nothing = match.group(1)
print(" going to", nothing)
else:
break
所以如果我运行 2.x 版本,它工作正常,通过循环,抓取 url 并走到最后,我得到以下输出:
and the next nothing is 72198
going to 72198
and the next nothing is 80992
going to 80992
and the next nothing is 8880
going to 8880 etc
如果我运行 3.x 版本,我会得到以下输出:
b'and the next nothing is 44827'
Traceback (most recent call last):
File "C:\Python32\lvl4.py", line 26, in <module>
match = findnothing(b"text")
TypeError: can't use a string pattern on a bytes-like object
所以如果我在这一行中将 r 更改为 a b
findnothing = re.compile(b"nothing is (\d+)").search
我明白了:
b'and the next nothing is 44827'
going to b'44827'
Traceback (most recent call last):
File "C:\Python32\lvl4.py", line 24, in <module>
text = urllib.request.urlopen(prefix + nothing).read()
TypeError: Can't convert 'bytes' object to str implicitly
有什么想法吗?
我对编程很陌生,所以请不要咬我的头。
_bk201
【问题讨论】:
标签: python python-3.x python-2to3