Сейчас я прохожу испытание на python, и я поднялся на уровень 4, смотрите здесь Я изучаю 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 на ab в этой строке
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